-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
84 lines (71 loc) · 1.99 KB
/
util.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
package server
import (
"crypto/rand"
"encoding/base64"
"fmt"
"html/template"
"log"
"net/http"
"github.com/bakurits/fshare-server/db"
"github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin"
)
func randToken() string {
b := make([]byte, 32)
_, _ = rand.Read(b)
return base64.StdEncoding.EncodeToString(b)
}
// handlerWithUser gin handler function with user
type handlerWithUser func(user db.User, c *gin.Context)
// userExtractorMiddleware extracts user from session and passes it to handlerWithUser
func (s *Server) userExtractorMiddleware(handler handlerWithUser) gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
email := session.Get(EmailSessionKey)
if email == nil {
c.Redirect(http.StatusSeeOther, "/login")
return
}
u, err := s.Repository.Users.Get(email.(string))
if err != nil {
c.Redirect(http.StatusSeeOther, "/login")
return
}
handler(u, c)
}
}
func (s *Server) getLoginURL(state string) string {
return s.AuthConfig.AuthCodeURL(state)
}
// executeTemplate executes templates with given filenames
// if withLayout is true than template executes with layout file
func (s *Server) executeTemplate(w http.ResponseWriter, data interface{}, withLayout bool, fileNames ...string) {
tplRoot := s.StaticFileDir + "/tpls"
var files []string
if withLayout {
files = append(files, tplRoot+"/layout.gohtml")
}
for _, file := range fileNames {
files = append(files, tplRoot+"/"+file+".gohtml")
}
err := template.Must(template.ParseFiles(files...)).Execute(w, data)
if err != nil {
log.Println(err)
}
}
func (s *Server) getEmailFromPasswordRecoveryRequest(c *gin.Context) string {
session := sessions.Default(c)
email := ""
if token := c.Query("token"); token != "" {
info, err := s.Repository.PasswordRestoreRequests.Get(token)
if err == nil {
email = info.Email
}
} else {
email = session.Get(EmailSessionKey).(string)
}
return email
}
func sendMail(subject, body string, addr ...string) {
fmt.Println(body)
}