|
|
- package Auth
-
- import (
- "encoding/json"
- "net/http"
- "time"
-
- "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
- "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
-
- "github.com/gofrs/uuid"
- )
-
- type Credentials struct {
- Username string `json:"username"`
- Password string `json:"password"`
- }
-
- type loginResponse struct {
- Status string `json:"status"`
- Message string `json:"message"`
- AsymmetricPublicKey string `json:"asymmetric_public_key"`
- AsymmetricPrivateKey string `json:"asymmetric_private_key"`
- }
-
- func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey string) {
- var (
- status string = "error"
- returnJson []byte
- err error
- )
- if code > 200 && code < 300 {
- status = "success"
- }
-
- returnJson, err = json.MarshalIndent(loginResponse{
- Status: status,
- Message: message,
- AsymmetricPublicKey: pubKey,
- AsymmetricPrivateKey: privKey,
- }, "", " ")
- if err != nil {
- http.Error(w, "Error", http.StatusInternalServerError)
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
-
- // Return updated json
- w.WriteHeader(code)
- w.Write(returnJson)
- }
-
- func Login(w http.ResponseWriter, r *http.Request) {
- var (
- creds Credentials
- userData Models.User
- sessionToken uuid.UUID
- expiresAt time.Time
- err error
- )
-
- err = json.NewDecoder(r.Body).Decode(&creds)
- if err != nil {
- makeLoginResponse(w, http.StatusInternalServerError, "An error occurred", "", "")
- return
- }
-
- userData, err = Database.GetUserByUsername(creds.Username)
- if err != nil {
- makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "")
- return
- }
-
- if !CheckPasswordHash(creds.Password, userData.Password) {
- makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "")
- return
- }
-
- sessionToken, err = uuid.NewV4()
- if err != nil {
- makeLoginResponse(w, http.StatusInternalServerError, "An error occurred", "", "")
- return
- }
-
- expiresAt = time.Now().Add(1 * time.Hour)
-
- Sessions[sessionToken.String()] = Session{
- UserID: userData.ID.String(),
- Username: userData.Username,
- Expiry: expiresAt,
- }
-
- http.SetCookie(w, &http.Cookie{
- Name: "session_token",
- Value: sessionToken.String(),
- Expires: expiresAt,
- })
-
- makeLoginResponse(
- w,
- http.StatusOK,
- "Successfully logged in",
- userData.AsymmetricPublicKey,
- userData.AsymmetricPrivateKey,
- )
- }
|