-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest_delete_terminal.go
85 lines (69 loc) · 1.99 KB
/
rest_delete_terminal.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
package main
import (
"github.com/go-redis/redis/v8"
"knowlgraph.com/ent/terminal"
"knowlgraph.com/ent/user"
)
func deleteTerminal(c *Context) error {
var form struct {
ID int `form:"id" binding:"required"`
}
if err := c.ShouldBindQuery(&form); err != nil {
return c.BadRequest(err.Error())
}
userID, _ := c.Get(GinKeyUserID)
token := getRequestToken(c.Context)
terminalMap := make(map[int]string)
if err := GetV4Redis(RUser(userID.(int)), &terminalMap); err != nil {
return c.ServiceUnavailable(err.Error())
}
var currentTerminalID int
for k, v := range terminalMap {
if v == token {
currentTerminalID = k
break
}
}
if 0 == currentTerminalID {
return c.Unauthorized("The current terminal is not authorized")
}
if currentTerminalID == form.ID {
// 终端不能在有其他终端存在时,删除自己,所以
// 当请求删除的终端 ID 与当前操作终端的 ID 相同时,拒绝删除请求,
// 除非当前账号有且只有一个终端,即当前操作终端时,删除有效。
count, err := client.Terminal.
Query().
Where(terminal.HasUserWith(user.ID(userID.(int)))).
Count(ctx)
if err != nil {
return c.InternalServerError(err.Error())
}
if 1 < count {
return c.PreconditionFailed("Please delete other terminals first")
}
}
deleteTerminalToken := terminalMap[form.ID]
delete(terminalMap, form.ID)
d := rdb.TTL(ctx, RUser(userID.(int))).Val()
_, err := rdb.Pipelined(ctx, func(pipe redis.Pipeliner) error {
if err1 := SetV2RedisPipe(pipe, RUser(userID.(int)), &terminalMap, d); err1 != nil {
return err1
}
pipe.Del(ctx, RToken(deleteTerminalToken))
return nil
})
if err != nil {
return c.InternalServerError(err.Error())
}
count, err := client.Terminal.
Delete().
Where(terminal.ID(form.ID), terminal.HasUserWith(user.ID(userID.(int)))).
Exec(ctx)
if err != nil {
return c.InternalServerError(err.Error())
}
if 0 == count {
return c.NotFound("The terminal ID was not found")
}
return c.Ok(true)
}