forked from traPtitech/naro-portal-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
223 lines (186 loc) · 6.24 KB
/
main.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
220
221
222
223
package main
import (
"crypto/sha256"
"database/sql"
"errors"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/srinathgs/mysqlstore"
"golang.org/x/crypto/bcrypt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
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"`
}
var (
db *sqlx.DB
)
func main() {
_db, err := sqlx.Connect(
"mysql",
fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
os.Getenv("DB_USERNAME"),
os.Getenv("DB_PASSWORD"),
os.Getenv("DB_HOSTNAME"),
os.Getenv("DB_PORT"),
os.Getenv("DB_DATABASE")))
if err != nil {
log.Fatalf("Cannot Connect to Database: %s", err)
}
db = _db
store, err := mysqlstore.NewMySQLStoreFromConnection(db.DB, "sessions", "/", 60*60*24*14, []byte("secret-token"))
if err != nil {
panic(err)
}
e := echo.New()
e.Use(middleware.Logger())
e.Use(session.Middleware(store))
e.GET("/ping", func(c echo.Context) error {
return c.String(http.StatusOK, "pong")
})
e.POST("/login", postLoginHandler)
e.POST("/signup", postSignUpHandler)
withLogin := e.Group("")
withLogin.Use(checkLogin)
withLogin.GET("/cities/:cityName", getCityInfoHandler)
withLogin.POST("/post", postTextHandler)
withLogin.GET("/recent/:number", getRecentPostHandler)
withLogin.GET("/whoami", getWhoAmIHandler)
e.Start(":10500")
}
type Me struct {
Username string `json:"username,omitempty" db:"username"`
}
type postText struct {
Text string `json:"text,omitempty" db:"Text"`
Username string `json:"username,omitempty" db:"Username"`
TimeStamp time.Time `json:"timeStamp,omitempty" db:"Timestamp"`
}
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"`
}
func postSignUpHandler(c echo.Context) error {
req := LoginRequestBody{}
c.Bind(&req)
// もう少し真面目にバリデーションするべき
if req.Password == "" || req.Username == "" {
// エラーは真面目に返すべき
return c.String(http.StatusBadRequest, "項目が空です")
}
hashedPass, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
if err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("bcrypt generate error: %v", err))
}
// ユーザーの存在チェック
var count int
err = db.Get(&count, "SELECT COUNT(*) FROM `naro-portal-users` WHERE Username=?", req.Username)
if err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("db error: %v", err))
}
if count > 0 {
return c.String(http.StatusConflict, "ユーザーが既に存在しています")
}
_, err = db.Exec("INSERT INTO `naro-portal-users` (Username, HashedPass) VALUES (?, ?)", req.Username, hashedPass)
if err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("db error: %v", err))
}
return c.NoContent(http.StatusCreated)
}
func postLoginHandler(c echo.Context) error {
req := LoginRequestBody{}
c.Bind(&req)
user := User{}
err := db.Get(&user, "SELECT * FROM `naro-portal-users` WHERE username=?", req.Username)
if err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("db error: %v", err))
}
err = bcrypt.CompareHashAndPassword([]byte(user.HashedPass), []byte(req.Password))
if err != nil {
if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
return c.NoContent(http.StatusForbidden)
} 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 checkLogin(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.StatusForbidden, "please login")
}
c.Set("userName", sess.Values["userName"].(string))
return next(c)
}
}
func getCityInfoHandler(c echo.Context) error {
cityName := c.Param("cityName")
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 time2str(t time.Time) string {
// レシーバーtを、"YYYY-MM-DDTHH-MM-SSZZZZ"という形の文字列に変換する
return t.Format("2006-01-02T15:04:05Z07:00")
}
func postTextHandler(c echo.Context) error {
req := postText{}
c.Bind(&req)
clock := time.Now()
sess, err := session.Get("sessions", c)
if err != nil {
fmt.Println(err)
return c.String(http.StatusInternalServerError, "something wrong in getting session")
}
targetText := []byte(req.Text + sess.Values["userName"].(string))
sha256 := sha256.Sum256(targetText)
hashed := fmt.Sprintf("%x", sha256)
_, err = db.Exec("INSERT INTO `naro-portal-post` (Text, Username, Timestamp, HashedPost) VALUES (?, ?,?,?)", req.Text, sess.Values["userName"].(string), clock, hashed)
if err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("db error: %v", err))
}
return c.NoContent(http.StatusOK)
}
func getRecentPostHandler(c echo.Context) error {
number := c.Param("number")
resentPost := []postText{}
db.Select(&resentPost, "SELECT Text,Username,Timestamp FROM `naro-portal-post` ORDER BY Timestamp DESC LIMIT ?", number)
return c.JSON(http.StatusOK, resentPost)
}
func getWhoAmIHandler(c echo.Context) error {
sess, _ := session.Get("sessions", c)
return c.JSON(http.StatusOK, Me{
Username: sess.Values["userName"].(string),
})
}