-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers_link.go
More file actions
75 lines (64 loc) · 1.59 KB
/
handlers_link.go
File metadata and controls
75 lines (64 loc) · 1.59 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
package main
import (
"crypto/md5"
"fmt"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
)
var usedCodesMutex sync.RWMutex
var usedCodes = make(map[string]string)
var counter int64
func generateUniqueLinkCode() string {
for {
counter++
timestamp := time.Now().UnixNano()
hash := md5.Sum([]byte(fmt.Sprintf("%d-%d", timestamp, counter)))
code := strings.ToUpper(fmt.Sprintf("%x", hash)[:6])
usedCodesMutex.Lock()
defer usedCodesMutex.Unlock()
if _, exists := usedCodes[code]; !exists {
usedCodes[code] = ""
return code
}
time.Sleep(time.Nanosecond)
}
}
func getLinkCode(c *gin.Context) {
code := generateUniqueLinkCode()
c.JSON(200, gin.H{"code": code})
}
func linkCodeToAccount(c *gin.Context) {
code := c.Query("code")
usedCodesMutex.Lock()
defer usedCodesMutex.Unlock()
if _, exists := usedCodes[code]; exists {
user := c.MustGet("user").(*User)
usedCodes[code] = user.GetKey()
c.JSON(200, "Linked Successfully")
return
}
c.JSON(404, gin.H{"error": "No auth code found"})
}
func getLinkStatus(c *gin.Context) {
code := c.Query("code")
usedCodesMutex.RLock()
defer usedCodesMutex.RUnlock()
if val, exists := usedCodes[code]; exists && val != "" {
c.JSON(200, gin.H{"status": "linked"})
} else {
c.JSON(404, gin.H{"status": "not found"})
}
}
func getLinkedUser(c *gin.Context) {
code := c.Query("code")
usedCodesMutex.RLock()
defer usedCodesMutex.RUnlock()
if val, exists := usedCodes[code]; exists && val != "" {
c.JSON(200, gin.H{"linked": true, "token": val})
delete(usedCodes, code)
} else {
c.JSON(404, gin.H{"linked": false, "token": ""})
}
}