party/cmd/api/tokens.go
2026-04-08 07:51:15 +02:00

78 lines
1.7 KiB
Go

package main
import (
"errors"
"net/http"
"time"
"party.at/party/internal/data"
"party.at/party/internal/validator"
)
func (app *application) createAuthenticationTokenHandler(w http.ResponseWriter, r *http.Request) {
var input struct {
Email string `json:"email"`
Password string `json:"password"`
}
err := app.readJSON(w, r, &input)
if err != nil {
app.badRequestResponse(w, r, err)
return
}
// Validate the email and password provided by the client.
v := validator.New()
data.ValidateEmail(v, input.Email)
data.ValidatePasswordPlaintext(v, input.Password)
if !v.Valid() {
app.failedValidationResponse(w, r, v.Errors)
return
}
user, err := app.models.Users.GetByEmail(input.Email)
if err != nil {
switch {
case errors.Is(err, data.ErrRecordNotFound):
app.invalidCredentialsResponse(w, r)
default:
app.serverErrorResponse(w, r, err)
}
return
}
identities, err := app.models.UserIdentities.GetByUser(user.ID)
var authenticatedIdentity *data.UserIdentity
for _, user_identity := range identities {
match, err := user_identity.Password.Matches(input.Password)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
if match {
authenticatedIdentity = user_identity
break
}
}
if authenticatedIdentity == nil {
app.invalidCredentialsResponse(w, r)
return
}
token, err := app.models.Tokens.New(user.ID, authenticatedIdentity.ID, 24 * time.Hour, data.ScopeAuthentication)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
err = app.writeJSON(w, http.StatusCreated, envelope{"authentication_token": token}, nil)
if err != nil {
app.serverErrorResponse(w, r, err)
}
}