summaryrefslogtreecommitdiff
path: root/api/login.go
blob: ef4330438da83ddf070899fecb2f9223d2390741 (plain) (blame)
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
package api

import (
	"encoding/json"
	"net/http"

	"github.com/go-playground/validator/v10"
	redqdb "sinanmohd.com/redq/db"
)

type loginAPI struct {
	db       *redqdb.SafeDB
	validate *validator.Validate
	req      *RequestLogin
	resp     *ResponseLogin
}

type RequestLogin struct {
	Account *redqdb.Account `validate:"required"`
}

type ResponseLogin struct {
	Account *redqdb.Account
}

func newLogin(db *redqdb.SafeDB) *loginAPI {
	a := &loginAPI{}
	a.db = db
	a.validate = validator.New(validator.WithRequiredStructEnabled())

	return a
}

func (a *loginAPI) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	a.req = &RequestLogin{}
	a.resp = &ResponseLogin{}

	err := unmarshal(r.Body, a.req)
	if err == nil {
		err = a.validate.Struct(a.req)
	}
	if err != nil {
		handleError(err, rw, http.StatusUnprocessableEntity)
		return
	}

	err = a.req.Account.Login(a.db)
	if err != nil {
		handleError(err, rw, http.StatusUnauthorized)
		return
	}
	a.resp.Account = a.req.Account

	json, err := json.Marshal(a.resp)
	if err != nil {
		handleError(err, rw, http.StatusInternalServerError)
		return
	}

	rw.Write(json)
}