-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler.go
More file actions
92 lines (73 loc) · 1.94 KB
/
handler.go
File metadata and controls
92 lines (73 loc) · 1.94 KB
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
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type CheckPasswordRequest struct {
Password string `json:"password" binding:"required"`
}
type CheckPasswordResponse struct {
PasswordHash string `json:"passwordHash"`
BreachCount uint64 `json:"breachCount"`
IsLeaked bool `json:"leaked"`
}
type HashResponse struct {
Hash string `json:"hash"`
Count uint64 `json:"count"`
}
type ErrorResponse struct {
Error string `json:"error"`
}
func GetByHashHandler(ps *PasswordService) gin.HandlerFunc {
return func(c *gin.Context) {
passwordHash := c.Param("hash")
if passwordHash == "" {
respondWithError(c, http.StatusBadRequest, "Missing passwordHash param!")
return
}
passwordHashObj, err := ps.GetByHash(passwordHash)
if err != nil {
respondWithError(c, http.StatusInternalServerError, err.Error())
return
}
if passwordHashObj == nil {
respondWithError(c, http.StatusNotFound, "Hash not found")
return
}
c.JSON(http.StatusOK, HashResponse{
Hash: passwordHashObj.Hash,
Count: passwordHashObj.Count,
})
}
}
func CheckPasswordHandler(ps *PasswordService) gin.HandlerFunc {
return func(c *gin.Context) {
var request CheckPasswordRequest
if err := c.ShouldBindJSON(&request); err != nil {
respondWithError(c, http.StatusBadRequest, "Invalid request: password field is required")
return
}
hashedPassword := ps.HashPassword(request.Password)
passwordHash, err := ps.Check(hashedPassword)
if err != nil {
respondWithError(c, http.StatusInternalServerError, err.Error())
return
}
response := CheckPasswordResponse{
PasswordHash: hashedPassword,
BreachCount: 0,
IsLeaked: false,
}
if passwordHash != nil {
response.BreachCount = passwordHash.Count
response.IsLeaked = true
}
c.JSON(http.StatusOK, response)
}
}
func respondWithError(c *gin.Context, code int, message string) {
response := ErrorResponse{
Error: message,
}
c.JSON(code, response)
}