-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.go
109 lines (100 loc) · 2.29 KB
/
session.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"errors"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func session(c *gin.Context) {
cookie, err := c.Cookie("session")
if err == http.ErrNoCookie {
return
}
session, err := store.Verify(cookie)
if err != nil {
return
}
c.Set("user", User{
Email: session.User,
})
c.Next()
}
func authRequired(c *gin.Context) {
if _, ok := c.Get("user"); !ok {
c.AbortWithError(401, errors.New("unauthorized"))
return
}
c.Next()
}
func getUser(c *gin.Context) User {
return c.MustGet("user").(User)
}
// @Summary Sign up
// @Description Sign up
// @Accept json
// @Produce json
// @Param data body User true "User"
// @Success 200 {object} string
// @Failure 400 {object} string
// @Failure 401 {object} string
// @Router /signup [post]
func signup(c *gin.Context) {
var user User
if err := c.ShouldBind(&user); err != nil {
c.AbortWithError(400, fmt.Errorf("invalid request: %w", err))
return
}
if err := store.Register(user.Email, user.Password); err != nil {
c.AbortWithError(400, fmt.Errorf("failed to register: %w", err))
return
}
if err := user.Mkdir(); err != nil {
c.AbortWithError(500, err)
return
}
token, err := store.Login(user.Email, user.Password)
if err != nil {
c.AbortWithError(401, fmt.Errorf("failed to login: %w", err))
return
}
c.SetCookie("session", token, 60*60*24*7, "", "", false, true)
c.Status(200)
}
// @Summary Sign in
// @Description Sign in
// @Accept json
// @Produce json
// @Param data body User true "User"
// @Success 200 {object} string
// @Failure 400 {object} string
// @Failure 401 {object} string
// @Router /signin [post]
func signin(c *gin.Context) {
var user User
if err := c.ShouldBind(&user); err != nil {
c.AbortWithError(400, fmt.Errorf("invalid request: %w", err))
return
}
token, err := store.Login(user.Email, user.Password)
if err != nil {
c.AbortWithError(401, fmt.Errorf("failed to login: %w", err))
return
}
c.SetCookie("session", token, 60*60*24*7, "", "", false, true)
c.Status(200)
}
func logout(c *gin.Context) {
c.SetCookie("session", "", -1, "", "", false, false)
c.Status(200)
}
// @Summary Get status
// @Description Get status
// @Produce json
// @Success 200 {boolean} bool
// @Router /status [get]
func status(c *gin.Context) {
_, ok := c.Get("user")
c.JSON(200, gin.H{
"signedIn": ok,
})
}