/
admin.handler.go
111 lines (97 loc) · 2.55 KB
/
admin.handler.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
package handlers
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/smileinnovation/imannotate/api/admin"
"github.com/smileinnovation/imannotate/api/auth"
"github.com/smileinnovation/imannotate/api/project"
"github.com/smileinnovation/imannotate/api/user"
)
// AdminStats returns basic stats.
func AdminStats(c *gin.Context) {
ps := project.GetStats().CountProjects()
us := auth.GetStats().CountUsers()
c.JSON(http.StatusOK, map[string]int{
"projects": ps,
"users": us,
})
}
type projectstat struct {
Project *project.Project `json:"project"`
Annotations int `json:"annotations"`
Contributors int `json:"contributors"`
}
// AdminGetProjects returns the entire project lists.
func AdminGetProjects(c *gin.Context) {
prj := admin.Get().GetProjects()
stats := []projectstat{}
for _, p := range prj {
na := project.GetStats().CountAnnotations(p)
ct := project.GetContributors(p)
stats = append(stats, projectstat{
Project: p,
Annotations: na,
Contributors: len(ct),
})
}
c.JSON(http.StatusOK, stats)
}
type userstat struct {
User *user.User `json:"user"`
IsAdmin bool `json:"isAdmin"`
Projects int `json:"projects"`
}
func AdminGetUsers(c *gin.Context) {
stats := []userstat{}
users := admin.Get().GetUsers()
for _, u := range users {
s := userstat{User: u}
p := project.GetAll(u)
s.IsAdmin = admin.Get().IsAdmin(u)
s.Projects = len(p)
stats = append(stats, s)
}
c.JSON(http.StatusOK, stats)
}
func DeleteUser(c *gin.Context) {
uname := c.Param("name")
u := &user.User{}
var err error
if u, err = auth.Get(uname); err != nil {
c.JSON(http.StatusNotFound, "User not found")
return
}
if err = admin.Get().DeleteUser(u); err != nil {
log.Println(err)
c.JSON(http.StatusInternalServerError, err.Error())
return
}
c.JSON(http.StatusAccepted, u.ID+" deleted")
}
func SetAdmin(c *gin.Context) {
uid := c.Param("name")
u, err := auth.Get(uid)
if err != nil {
c.JSON(http.StatusInternalServerError, err.Error())
return
}
if err := admin.Get().SetAdmin(u); err != nil {
c.JSON(http.StatusInternalServerError, err.Error())
return
}
c.JSON(http.StatusAccepted, "user "+u.ID+" is now admin")
}
func RemoveAdmin(c *gin.Context) {
uid := c.Param("name")
u, err := auth.Get(uid)
if err != nil {
c.JSON(http.StatusInternalServerError, err.Error())
return
}
if err := admin.Get().RemoveAdmin(u); err != nil {
c.JSON(http.StatusInternalServerError, err.Error())
return
}
c.JSON(http.StatusAccepted, "user "+u.ID+" is now normal user")
}