forked from mirrors/pronouns.cc
62 lines
1.4 KiB
Go
62 lines
1.4 KiB
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"codeberg.org/pronounscc/pronouns.cc/backend/server"
|
|
"emperror.dev/errors"
|
|
"github.com/go-chi/render"
|
|
"github.com/rs/xid"
|
|
)
|
|
|
|
type postLoginRequest struct {
|
|
Email string `json:"email"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
type postLoginResponse struct {
|
|
User *userResponse `json:"user,omitempty"`
|
|
Token string `json:"token,omitempty"`
|
|
}
|
|
|
|
func (s *Server) postLogin(w http.ResponseWriter, r *http.Request) (err error) {
|
|
ctx := r.Context()
|
|
var req postLoginRequest
|
|
err = render.Decode(r, &req)
|
|
if err != nil {
|
|
return server.APIError{Code: server.ErrBadRequest}
|
|
}
|
|
|
|
u, err := s.DB.UserByEmail(ctx, req.Email)
|
|
if err != nil {
|
|
return server.APIError{Code: server.ErrForbidden, Details: "Invalid email or password"}
|
|
}
|
|
|
|
if !u.VerifyPassword(req.Password) {
|
|
return server.APIError{Code: server.ErrForbidden, Details: "Invalid email or password"}
|
|
}
|
|
|
|
tokenID := xid.New()
|
|
token, err := s.Auth.CreateToken(u.ID, tokenID, u.IsAdmin, false, true)
|
|
if err != nil {
|
|
return errors.Wrap(err, "creating token")
|
|
}
|
|
|
|
// save token to database
|
|
_, err = s.DB.SaveToken(ctx, s.DB, u.ID, tokenID, false, false)
|
|
if err != nil {
|
|
return errors.Wrap(err, "saving token to database")
|
|
}
|
|
|
|
fields, err := s.DB.UserFields(ctx, u.ID)
|
|
if err != nil {
|
|
return errors.Wrap(err, "querying fields")
|
|
}
|
|
|
|
render.JSON(w, r, postLoginResponse{
|
|
Token: token,
|
|
User: dbUserToUserResponse(u, fields),
|
|
})
|
|
|
|
return nil
|
|
}
|