-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathotp.go
276 lines (217 loc) · 6.16 KB
/
otp.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package otp_golang
import (
"errors"
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v4"
"gorm.io/gorm"
"math/rand"
"os"
"strconv"
"time"
)
const (
PathAuth = "/auth"
PathRegister = "/register"
PathLogin = "/login"
PathOtp = "/otp"
PathGetUser = "/user"
LocalUser = "user_model"
LocalClaims = "claims"
)
type Auth struct {
App *fiber.App
DB *gorm.DB
Config Config
}
type Config struct {
OtpHandler fiber.Handler
LoginHandler fiber.Handler
RegisterHandler fiber.Handler
GetUserHandler fiber.Handler
AuthMiddleware fiber.Handler
SmsProvider ISmsProvider
UserRepository IUserRepository
OtpCodeRepository OtpCodeRepository
SendOtp func(phone string, code string) error
}
type OtpModel struct {
Phone string `json:"phone"`
}
type OtpBaseUserModel struct {
Phone string `json:"phone"`
}
type OtpCode struct {
ID uint `gorm:"primarykey"`
Phone string `json:"phone"`
Code string `json:"code"`
ExpiredAt time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
func (o OtpCode) IsExpired() bool {
return !time.Now().Before(o.ExpiredAt)
}
type OtpCheckerResponse struct {
Authenticated bool
Registered bool
Phone string
Expiration time.Time
}
type Router struct {
LoginPrefix string
RegisterPrefix string
}
type HeaderBearer struct {
Authorization string `reqHeader:"Authorization"`
}
type ISmsProvider interface {
SendOtp(phone string, code string) error
}
type IUserRepository interface {
Register(parser func(interface{}) error) error
Registered(phone string) bool
FindByPhone(phone string) (interface{}, error)
}
func New(app *fiber.App, db *gorm.DB, config Config) *Auth {
auth := &Auth{
App: app,
DB: db,
Config: config,
}
return auth
}
func (a *Auth) Initialize() {
if a.Config.OtpHandler == nil {
a.Config.OtpHandler = a.otpHandler
}
if a.Config.LoginHandler == nil {
a.Config.LoginHandler = a.loginHandler
}
if a.Config.RegisterHandler == nil {
a.Config.RegisterHandler = a.registerHandler
}
if a.Config.AuthMiddleware == nil {
a.Config.AuthMiddleware = AuthMiddleware
}
if a.Config.GetUserHandler == nil {
a.Config.GetUserHandler = a.getUserHandler
}
a.Config.OtpCodeRepository.DB = a.DB
a.SetRoutes()
}
func (a *Auth) SetRoutes() {
authRouter := a.App.Group("/auth")
authRouter.Post(PathOtp, a.Config.OtpHandler)
authRouter.Post(PathLogin, a.Config.LoginHandler)
authRouter.Post(PathRegister, a.Config.AuthMiddleware, a.Config.RegisterHandler)
authRouter.Get(PathGetUser, a.Config.AuthMiddleware, a.Config.GetUserHandler)
}
func (a *Auth) SetSmsProvider(provider ISmsProvider) {
a.Config.SmsProvider = provider
}
func (a *Auth) SetUserRepository(subject IUserRepository) {
a.Config.UserRepository = subject
}
func (a *Auth) loginHandler(c *fiber.Ctx) error {
var otpCheckerResponse OtpCheckerResponse
phone := c.FormValue("phone")
code := c.FormValue("code")
otpCode, e := a.Config.OtpCodeRepository.Validate(phone, code)
if otpCheckerResponse.Authenticated = e == nil; otpCheckerResponse.Authenticated {
otpCheckerResponse.Registered = a.Config.UserRepository.Registered(phone)
claims := jwt.MapClaims{
"registered": otpCheckerResponse.Registered,
"otp": code,
"phone": phone,
"exp": otpCode.ExpiredAt.Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
t, err := token.SignedString([]byte(os.Getenv("JWT_SECRET_KEY")))
if err != nil {
return c.SendStatus(fiber.StatusInternalServerError)
}
return c.JSON(fiber.Map{
"token": t,
"phone": phone,
"registered": otpCheckerResponse.Registered,
"expiration": otpCheckerResponse.Expiration,
})
}
return c.Status(422).JSON("Otp Code Is Wrong")
}
// registerHandler function only stands for setting columns to user table
func (a *Auth) registerHandler(c *fiber.Ctx) error {
e := a.Config.UserRepository.Register(c.BodyParser)
if e != nil {
return c.Status(422).JSON("Something went wrong")
}
return c.JSON("registered user")
}
// getUserHandler gets user from db
func (a *Auth) getUserHandler(c *fiber.Ctx) error {
claims := c.Locals("claims").(jwt.MapClaims)
if userData, e := a.Config.UserRepository.FindByPhone(claims["phone"].(string)); e == nil {
return c.JSON(userData)
}
return c.SendStatus(fiber.StatusNotFound)
}
// otpHandler will be creating and sending otp code
func (a *Auth) otpHandler(c *fiber.Ctx) error {
phone := c.FormValue("phone")
otpCode := createOtpCode()
a.Config.OtpCodeRepository.Insert(phone, otpCode, time.Now().Add(time.Hour*72))
e := a.Config.SmsProvider.SendOtp(phone, otpCode)
if e != nil {
fmt.Println(e.Error())
return c.SendStatus(fiber.StatusInternalServerError)
}
return c.JSON("Code Sent")
}
func (a *Auth) GetRegisterPath() string {
return PathAuth + PathRegister
}
func (a *Auth) GetLoginPath() string {
return PathAuth + PathLogin
}
func (a *Auth) GetOtpPath() string {
return PathAuth + PathOtp
}
func (a *Auth) GetUserHandler(ctx *fiber.Ctx) error {
claims := ctx.Locals(LocalClaims).(jwt.MapClaims)
if user, err := a.Config.UserRepository.FindByPhone(claims["phone"].(string)); err == nil {
ctx.Locals(LocalUser, user)
}
return ctx.SendStatus(fiber.StatusNotFound)
}
// createOtpCode is a helper for creating six digits otp codes
func createOtpCode() string {
min := 100000
max := 999999
rand.Seed(time.Now().UnixNano())
return strconv.Itoa(rand.Intn(max-min) + min)
}
type GormRepository struct {
DB *gorm.DB
}
type OtpCodeRepository struct {
GormRepository
OtpCode OtpCode
}
func (repository OtpCodeRepository) Validate(phone string, otp string) (OtpCode, error) {
var err error
result := repository.DB.Where("phone = ? AND code = ?", phone, otp).Last(&repository.OtpCode)
if result.Error != nil {
err = errors.New("invalid Otp Code")
}
if time.Now().After(repository.OtpCode.ExpiredAt) {
err = errors.New("otp code expired")
}
return repository.OtpCode, err
}
func (repository OtpCodeRepository) Insert(phone string, code string, expiredAt time.Time) {
repository.OtpCode.Phone = phone
repository.OtpCode.Code = code
repository.OtpCode.ExpiredAt = expiredAt
repository.DB.Create(&repository.OtpCode)
}