aboutsummaryrefslogtreecommitdiffstats
path: root/api/handlers/users.go
blob: 3a1788dcc26b3e353f563c35aea278466a822644 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package handlers

import (
	"errors"
	"net/http"

	"github.com/LMBishop/confplanner/api/dto"
	"github.com/LMBishop/confplanner/pkg/auth"
	"github.com/LMBishop/confplanner/pkg/session"
	"github.com/LMBishop/confplanner/pkg/user"
)

func Register(userService user.Service, authService auth.Service) http.HandlerFunc {
	return dto.WrapResponseFunc(func(w http.ResponseWriter, r *http.Request) error {
		var request dto.RegisterRequest
		if err := dto.ReadDto(r, &request); err != nil {
			return err
		}

		basicAuthProvider := authService.GetAuthProvider("basic")
		if _, ok := basicAuthProvider.(*auth.BasicAuthProvider); !ok {
			return &dto.ErrorResponse{
				Code:    http.StatusForbidden,
				Message: "Registrations are only accepted via an identity provider",
			}
		}

		createdUser, err := userService.CreateUser(request.Username, request.Password)
		if err != nil {
			if errors.Is(err, user.ErrUserExists) {
				return &dto.ErrorResponse{
					Code:    http.StatusConflict,
					Message: "User with that username already exists",
				}
			} else if errors.Is(err, user.ErrNotAcceptingRegistrations) {
				return &dto.ErrorResponse{
					Code:    http.StatusForbidden,
					Message: "This service is not currently accepting registrations",
				}
			}

			return err
		}

		return &dto.OkResponse{
			Code: http.StatusCreated,
			Data: &dto.RegisterResponse{
				ID: createdUser.ID,
			},
		}
	})
}

func Logout(store session.Service) http.HandlerFunc {
	return dto.WrapResponseFunc(func(w http.ResponseWriter, r *http.Request) error {
		session := r.Context().Value("session").(*session.UserSession)

		err := store.Destroy(session.SessionID)
		if err != nil {
			return err
		}

		return &dto.OkResponse{
			Code: http.StatusNoContent,
		}
	})
}