generated from traPtitech/naro-template-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
219 lines (184 loc) · 5.87 KB
/
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
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
package main
import (
"database/sql"
"errors"
"fmt"
"log"
"net/http"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"golang.org/x/crypto/bcrypt"
)
type City struct {
ID int `json:"id,omitempty" db:"ID"`
Name sql.NullString `json:"name,omitempty" db:"Name"`
CountryCode sql.NullString `json:"countryCode,omitempty" db:"CountryCode"`
District sql.NullString `json:"district,omitempty" db:"District"`
Population sql.NullInt64 `json:"population,omitempty" db:"Population"`
}
type Country struct {
CountryName sql.NullString `json:"countryName,omitempty" db:"Name"`
}
type LoginRequestBody struct {
Username string `json:"username,omitempty" form:"username"`
Password string `json:"password,omitempty" form:"password"`
}
type User struct {
Username string `json:"username,omitempty" db:"Username"`
HashedPass string `json:"-" db:"HashedPass"`
}
type Me struct {
Username string `json:"username,omitempty" db:"username"`
}
func getCityInfoHandler(c echo.Context) error {
cityName := c.Param("cityName")
fmt.Println(cityName)
var city City
db.Get(&city, "SELECT * FROM city WHERE Name=?", cityName)
if !city.Name.Valid {
return c.NoContent(http.StatusNotFound)
}
return c.JSON(http.StatusOK, city)
}
func postCityHandler(c echo.Context) error {
var city City
err := c.Bind(&city)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "bad request body")
}
result, err := db.Exec("INSERT INTO city (Name, CountryCode, District, Population) VALUES (?, ?, ?, ?)", city.Name, city.CountryCode, city.District, city.Population)
if err != nil {
log.Printf("failed to insert city data: %s\n", err)
return c.NoContent(http.StatusInternalServerError)
}
id, err := result.LastInsertId()
if err != nil {
fmt.Printf("failed to get last insert id: %s\n", err)
return c.NoContent(http.StatusInternalServerError)
}
city.ID = int(id)
return c.JSON(http.StatusCreated, city)
}
func getCountryListHandler(c echo.Context) error {
var countries []Country
err := db.Select(&countries, "SELECT Name FROM country")
if err != nil {
fmt.Println(err)
return c.String(http.StatusInternalServerError, "something wrong in getting country list")
}
return c.JSON(http.StatusOK, countries)
}
func getCityListHandler(c echo.Context) error {
var cities []City
var countryCode string
countryName := c.Param("countryName")
err := db.Get(&countryCode, "SELECT code FROM country WHERE name=?",countryName)
if err != nil {
fmt.Println(err)
return c.String(http.StatusInternalServerError, "something wrong in getting countrycode")
}
err = db.Select(&cities, "SELECT * FROM city WHERE countrycode=?",countryCode)
if err != nil {
fmt.Println(err)
return c.String(http.StatusInternalServerError, "something wrong in getting city list")
}
return c.JSON(http.StatusOK, cities)
}
func signUpHandler(c echo.Context) error {
var req LoginRequestBody
c.Bind(&req)
if req.Password == "" || req.Username == "" {
return c.String(http.StatusBadRequest, "Username or Password is empty")
}
var count int
err := db.Get(&count, "SELECT COUNT(*) FROM users WHERE Username=?", req.Username)
if err != nil {
log.Println(err)
return c.NoContent(http.StatusInternalServerError)
}
if count > 0 {
return c.String(http.StatusConflict, "Username is already used")
}
pw := req.Password + salt
hashedPass, err := bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost)
if err != nil {
log.Println(err)
return c.NoContent(http.StatusInternalServerError)
}
_, err = db.Exec("INSERT INTO users (Username, HashedPass) VALUES (?, ?)", req.Username, hashedPass)
if err != nil {
log.Println(err)
return c.NoContent(http.StatusInternalServerError)
}
return c.NoContent(http.StatusCreated)
}
func loginHandler(c echo.Context) error {
var req LoginRequestBody
c.Bind(&req)
if req.Password == "" || req.Username == "" {
return c.String(http.StatusBadRequest, "Username or Password is empty")
}
user := User{}
err := db.Get(&user, "SELECT * FROM users WHERE username=?", req.Username)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return c.NoContent(http.StatusUnauthorized)
} else {
log.Println(err)
return c.NoContent(http.StatusInternalServerError)
}
}
err = bcrypt.CompareHashAndPassword([]byte(user.HashedPass), []byte(req.Password + salt))
if err != nil {
if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
return c.NoContent(http.StatusUnauthorized)
} else {
return c.NoContent(http.StatusInternalServerError)
}
}
sess, err := session.Get("sessions", c)
if err != nil {
fmt.Println(err)
return c.String(http.StatusInternalServerError, "something wrong in getting session")
}
sess.Values["userName"] = req.Username
sess.Save(c.Request(), c.Response())
return c.NoContent(http.StatusOK)
}
func logoutHandler(c echo.Context) error {
sess, err := session.Get("sessions", c)
if err != nil {
fmt.Println(err)
return c.String(http.StatusInternalServerError, "something wrong in logout")
}
sess.Values["username"] = nil
return c.NoContent(http.StatusOK)
}
func userAuthMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
sess, err := session.Get("sessions", c)
if err != nil {
fmt.Println(err)
return c.String(http.StatusInternalServerError, "something wrong in getting session")
}
if sess.Values["userName"] == nil {
return c.String(http.StatusUnauthorized, "please login")
}
c.Set("userName", sess.Values["userName"].(string))
return next(c)
}
}
func getWhoAmIHandler(c echo.Context) error {
return c.JSON(http.StatusOK, Me{
Username: c.Get("userName").(string),
})
}
func calculatePopulationSumHandler(cities []City) map[string]int{
output := make(map[string]int)
for _, cityInfo := range cities {
if cityInfo.CountryCode.Valid {
output[cityInfo.CountryCode.String] += int(cityInfo.Population.Int64)
}
}
return output
}