|
| 1 | +package auth |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "net/http" |
| 6 | + |
| 7 | + "github.com/gomantics/semantix/config" |
| 8 | + "github.com/gomantics/semantix/internal/api/web" |
| 9 | + "github.com/gomantics/semantix/internal/domains/users" |
| 10 | + "go.uber.org/zap" |
| 11 | +) |
| 12 | + |
| 13 | +type SignupRequest struct { |
| 14 | + Email string `json:"email"` |
| 15 | + Password string `json:"password"` |
| 16 | +} |
| 17 | + |
| 18 | +func Signup(c web.Context) error { |
| 19 | + var req SignupRequest |
| 20 | + if err := c.Bind(&req); err != nil { |
| 21 | + return c.BadRequest("invalid request body") |
| 22 | + } |
| 23 | + |
| 24 | + if req.Email == "" { |
| 25 | + return c.BadRequest("email is required") |
| 26 | + } |
| 27 | + if len(req.Password) < 8 { |
| 28 | + return c.BadRequest("password must be at least 8 characters") |
| 29 | + } |
| 30 | + |
| 31 | + ctx := c.Request().Context() |
| 32 | + |
| 33 | + user, err := users.CreateFirst(ctx, users.CreateParams{ |
| 34 | + Email: req.Email, |
| 35 | + Password: req.Password, |
| 36 | + }) |
| 37 | + if err != nil { |
| 38 | + if errors.Is(err, users.ErrAdminExists) { |
| 39 | + return c.Error(http.StatusForbidden, "admin user already exists") |
| 40 | + } |
| 41 | + c.L.Error("failed to create user", zap.Error(err)) |
| 42 | + return c.InternalError("failed to create user") |
| 43 | + } |
| 44 | + |
| 45 | + token, err := users.CreateSession(ctx, user.ID) |
| 46 | + if err != nil { |
| 47 | + c.L.Error("failed to create session", zap.Error(err)) |
| 48 | + return c.InternalError("failed to create session") |
| 49 | + } |
| 50 | + |
| 51 | + c.SetCookie(sessionCookie(token)) |
| 52 | + |
| 53 | + return c.Created(map[string]any{ |
| 54 | + "id": user.ID, |
| 55 | + "email": user.Email, |
| 56 | + }) |
| 57 | +} |
| 58 | + |
| 59 | +func sessionCookie(token string) *http.Cookie { |
| 60 | + return &http.Cookie{ |
| 61 | + Name: "session_token", |
| 62 | + Value: token, |
| 63 | + Path: "/", |
| 64 | + HttpOnly: true, |
| 65 | + SameSite: http.SameSiteStrictMode, |
| 66 | + Secure: config.IsProd(), |
| 67 | + } |
| 68 | +} |
0 commit comments