]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git/blob - api/api.go
Mails.
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git] / api / api.go
1 package api
2
3 import (
4 "net/http"
5 "unicode"
6
7 "github.com/gin-gonic/gin"
8 )
9
10 var CONFIG Config
11 var MAIL_CONFIG MailConfig
12
13 type MailConfig struct {
14 IsEnabled bool
15 SmtpAddress string `toml:"smtp_address"`
16 AddressFrom string `toml:"address_from"`
17 Login string `toml:"login"`
18 Password string `toml:"password"`
19 }
20
21 type Config struct {
22 Domain string `toml:"domain"`
23 JwtSecret string `toml:"jwt_secret"`
24 PasswordResetSecret string `toml:"password_reset_secret"`
25 FreeSMSUser string `toml:"free_sms_user"`
26 FreeSMSPass string `toml:"free_sms_pass"`
27 }
28
29 func SetConfig(config Config) {
30 CONFIG = config
31
32 JWT_SECRET = []byte(config.JwtSecret)
33 PASSWORD_RESET_SECRET = []byte(config.PasswordResetSecret)
34 }
35
36 func SetMailConfig(config MailConfig) {
37 MAIL_CONFIG = config
38
39 if config.Login != "" && config.AddressFrom != "" && config.Password != "" && config.SmtpAddress != "" {
40 MAIL_CONFIG.IsEnabled = true
41 ConfigureMailTemplateEngine()
42 }
43 }
44
45 type Error struct {
46 Code ErrorCode
47 UserMessage string
48 err error
49 }
50
51 func (e Error) Err() error {
52 if e.err != nil {
53 return e
54 }
55
56 return nil
57 }
58
59 func (e Error) Error() string {
60 if e.err != nil {
61 return e.err.Error()
62 }
63
64 return ""
65 }
66
67 func ErrorIs(err error, code ErrorCode) bool {
68 if err == nil {
69 return false
70 }
71
72 if apiError, ok := err.(*Error); !ok {
73 return false
74 } else {
75 return apiError.Code == code
76 }
77 }
78
79 func NewInternalError(err error) *Error {
80 if apiError, ok := err.(*Error); ok {
81 return apiError
82 }
83 return &Error{InternalError, "internal error", err}
84 }
85
86 func ToSnake(in string) string {
87 runes := []rune(in)
88 length := len(runes)
89
90 var out []rune
91 for i := 0; i < length; i++ {
92 if i > 0 && unicode.IsUpper(runes[i]) && ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
93 out = append(out, '_')
94 }
95 out = append(out, unicode.ToLower(runes[i]))
96 }
97
98 return string(out)
99 }
100
101 type Response struct {
102 StatusCode Status `json:"-"`
103 ErrorCode ErrorCode `json:"-"`
104
105 Status string `json:"status"`
106 Code string `json:"code,omitempty"`
107 Response interface{} `json:"response,omitempty"`
108 Message string `json:"message,omitempty"`
109 }
110
111 func (r Response) populateStatus() Response {
112 r.Status = ToSnake(r.StatusCode.String())
113
114 if r.ErrorCode != 0 {
115 r.Code = ToSnake(r.ErrorCode.String())
116 }
117
118 return r
119 }
120
121 func ErrorResponse(code ErrorCode, message string) Response {
122 return Response{
123 StatusCode: NOK,
124 ErrorCode: code,
125 Message: message,
126 }
127 }
128
129 func SuccessResponse(data interface{}) Response {
130 return Response{
131 StatusCode: OK,
132 Response: data,
133 }
134 }
135
136 func WriteJsonResponse(response Response, c *gin.Context) {
137 response = response.populateStatus()
138
139 c.JSON(StatusToHttpCode(response.StatusCode, response.ErrorCode), response)
140 }
141
142 func WriteBinary(contentType string, b []byte, c *gin.Context) {
143 c.Data(http.StatusOK, contentType, b)
144 }
145
146 type Middleware func(*gin.Context) *Error
147
148 func M(handler Middleware) gin.HandlerFunc {
149 return func(c *gin.Context) {
150 err := handler(c)
151
152 if err != nil {
153 WriteJsonResponse(ErrorResponse(err.Code, err.UserMessage), c)
154 c.Error(err)
155 c.Abort()
156 } else {
157 c.Next()
158 }
159 }
160 }
161
162 type Query interface {
163 ValidateParams() *Error
164 Run() (interface{}, *Error)
165 }
166
167 func RunQuery(query Query, c *gin.Context) {
168 if err := query.ValidateParams(); err != nil {
169 WriteJsonResponse(ErrorResponse(err.Code, err.UserMessage), c)
170 c.Error(err)
171 return
172 }
173
174 if out, err := query.Run(); err != nil {
175 WriteJsonResponse(ErrorResponse(err.Code, err.UserMessage), c)
176 c.Error(err)
177 } else {
178 WriteJsonResponse(SuccessResponse(out), c)
179 }
180 }