implemented login logic
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func RegisterHandler(response http.ResponseWriter, request *http.Request) {
|
||||
if request.Method != http.MethodPost {
|
||||
http.Error(response, "POST only", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
ctx := request.Context()
|
||||
username := request.FormValue("username")
|
||||
password := request.FormValue("password")
|
||||
|
||||
if len(username) < 2 {
|
||||
http.Error(response, "short username", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if len(password) < 8 {
|
||||
http.Error(response, "short password", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := GetUserDataByName(ctx, username); err == nil {
|
||||
http.Error(response, "User already exists", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := AddNewUser(ctx, User{0, username, password, "xxx", false}); err != nil {
|
||||
http.Error(response, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func LoginHandler(response http.ResponseWriter, request *http.Request) {
|
||||
if request.Method != http.MethodPost {
|
||||
http.Error(response, "POST only", http.StatusMethodNotAllowed)
|
||||
}
|
||||
ctx := request.Context()
|
||||
username := request.FormValue("username")
|
||||
password := request.FormValue("password")
|
||||
|
||||
if len(username) < 2 {
|
||||
http.Error(response, "short username", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := GetUserDataByName(ctx, username)
|
||||
if err != nil {
|
||||
http.Error(response, "Bad login", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) == nil {
|
||||
token, err := GetToken(user)
|
||||
if err != nil {
|
||||
http.Error(response, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err = response.Write([]byte(token)); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user