Advertisement
Guest User

Untitled

a guest
Mar 10th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.99 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "github.com/dgrijalva/jwt-go"
  7. "github.com/gorilla/mux"
  8. "io"
  9. "io/ioutil"
  10. "log"
  11. "net/http"
  12. "os"
  13. "os/exec"
  14. "sort"
  15. "strconv"
  16. )
  17.  
  18. // ToDo бахнуть обработку ошибок
  19.  
  20. type User struct {
  21. ID string
  22. Nickname string `json:"nickname"`
  23. Email string `json:"email"`
  24. Password string `json:"password"`
  25. Points int
  26. Age int
  27. ImgUrl string
  28. Region string
  29. About string
  30. }
  31.  
  32. type Order struct {
  33. Sequence string `json:"order"`
  34. }
  35.  
  36. //ToDo: Move to another package
  37. var errorLogin = map[string]string{
  38. "Error": "User dont exist",
  39. }
  40.  
  41. var errorCreateUser = map[string]string{
  42. "Error": "Nickname/mail already exists",
  43. }
  44.  
  45. var users []User
  46.  
  47. func (u *User) setUniqueId() {
  48. // DB incremental or smth
  49. out, _ := exec.Command("uuidgen").Output()
  50. u.Points = 0
  51. u.ID = string(out[:len(out)-1])
  52. }
  53.  
  54. func createUser(w http.ResponseWriter, r *http.Request) {
  55. w.Header().Set("Content-Type", "application/json")
  56. var newUser User
  57. _ = json.NewDecoder(r.Body).Decode(&newUser) // ToDo: Log error
  58. for _, existUser := range users {
  59. if newUser.Nickname == existUser.Nickname || newUser.Email == existUser.Email {
  60. json.NewEncoder(w).Encode(errorCreateUser)
  61. return
  62. }
  63. }
  64. newUser.setUniqueId()
  65. users = append(users, newUser) // Check succesfull append? ( in db clearly )
  66. //json.NewEncoder(w).Encode(newUser)
  67.  
  68. }
  69.  
  70. //ToDo: Use get with key order? (ASC/DESC )
  71. //ToDo: Check and simplify conditions !!!
  72. func getLeaderboard(w http.ResponseWriter, r *http.Request) {
  73. w.Header().Set("Content-Type", "application/json")
  74. var order Order
  75. var pageSize int
  76. // Initilize pagesize
  77. pageSize = 1
  78. _ = json.NewDecoder(r.Body).Decode(&order)
  79. sort.Slice(users, func(i, j int) bool {
  80. return users[i].Points > users[j].Points
  81. })
  82. offset, getOffset := r.URL.Query()["offset"]
  83. if getOffset {
  84. offsetInt, _ := strconv.ParseInt(offset[0], 10, 32) // ToDo Handle error
  85. if int(offsetInt) > len(users) {
  86. json.NewEncoder(w).Encode(users)
  87. return
  88. } else if int(offsetInt) == len(users) {
  89. json.NewEncoder(w).Encode(users)
  90. return
  91. }
  92. if int(offsetInt)+pageSize < len(users) {
  93. json.NewEncoder(w).Encode(users[offsetInt : int(offsetInt)+pageSize])
  94. return
  95. } else {
  96. json.NewEncoder(w).Encode(users[offsetInt:len(users)])
  97. return
  98. }
  99. } else {
  100. if pageSize < len(users) {
  101. json.NewEncoder(w).Encode(users[:pageSize])
  102. return
  103. } else {
  104. json.NewEncoder(w).Encode(users)
  105. return
  106. }
  107. }
  108.  
  109. }
  110.  
  111. func createSessionId(user User) string {
  112. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  113. "id": user.ID,
  114. "nickname": user.Nickname,
  115. "email": user.Email,
  116. "about": user.About,
  117. "region": user.Region,
  118. "img": user.ImgUrl,
  119. "age": user.Age,
  120. })
  121. // ToDo: Error handle
  122. spiceSalt, _ := ioutil.ReadFile("secret.conf")
  123. secretStr, _ := token.SignedString(spiceSalt)
  124. return secretStr
  125. }
  126.  
  127. func checkAuth(cookie *http.Cookie) jwt.MapClaims {
  128. token, _ := jwt.Parse(cookie.Value, func(token *jwt.Token) (interface{}, error) {
  129. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  130. return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
  131. }
  132. spiceSalt, _ := ioutil.ReadFile("secret.conf")
  133. return spiceSalt, nil
  134. })
  135.  
  136. claims, _ := token.Claims.(jwt.MapClaims)
  137.  
  138. // ToDo: Handle else case
  139. return claims
  140. }
  141.  
  142.  
  143.  
  144. func isAuth (w http.ResponseWriter, r *http.Request) {
  145. //authflag := false
  146. cookie, err := r.Cookie("session_id")
  147. fmt.Println(cookie.Path)
  148. if err != nil {
  149. w.Write([]byte("=("))
  150. return
  151. }
  152.  
  153. claims := checkAuth(cookie)
  154. for _, user := range users {
  155. if user.Nickname == claims["nickname"].(string) {
  156. json.NewEncoder(w).Encode(map[string]bool{"is_auth": true, })
  157. return
  158. }
  159. }
  160. json.NewEncoder(w).Encode(map[string]bool{"is_auth": false, })
  161. }
  162.  
  163. func editUser(w http.ResponseWriter, r *http.Request) {
  164. //Checking cookie
  165. cookie, err := r.Cookie("session_id")
  166. fmt.Println(cookie.Path)
  167. if err != nil {
  168. w.Write([]byte("=("))
  169. return
  170. }
  171. // Taking JSON of modified user from edit form
  172. var modUser User
  173. _ = json.NewDecoder(r.Body).Decode(&modUser)
  174. // Getting claims from current cookie
  175. claims := checkAuth(cookie)
  176.  
  177. // Finding user from claims in users and changing old data to modified data
  178. for _, user := range users {
  179. if user.ID == claims["nickname"].(string) {
  180. u := &user
  181. if modUser.Nickname != "" {
  182. u.Nickname = modUser.Nickname
  183. }
  184. if modUser.Email != "" {
  185. u.Email = modUser.Email
  186. }
  187. if modUser.Password != "" {
  188. u.Password = modUser.Password
  189. }
  190. if modUser.Region != "" {
  191. u.Region = modUser.Region
  192. }
  193. if modUser.Age != 0 {
  194. u.Age = modUser.Age
  195. }
  196. if modUser.About != "" {
  197. u.About = modUser.About
  198. }
  199. if modUser.ImgUrl != "" {
  200. u.ImgUrl = modUser.ImgUrl
  201. }
  202. json.NewEncoder(w).Encode(*u)
  203. break
  204. }
  205. }
  206. }
  207.  
  208. func login(w http.ResponseWriter, r *http.Request) {
  209. var sessionId string
  210. var userExistFlag bool
  211. var existUser User
  212. _ = json.NewDecoder(r.Body).Decode(&existUser)
  213. for _, user := range users {
  214. if user.Nickname == existUser.Nickname && user.Password == existUser.Password {
  215. userExistFlag = true
  216. existUser = user
  217. }
  218. }
  219. if !userExistFlag {
  220. json.NewEncoder(w).Encode(errorLogin)
  221. return
  222. }
  223. sessionId = createSessionId(existUser)
  224. fmt.Println(sessionId)
  225. cookie := &http.Cookie{
  226. Name: "session_id",
  227. Value: sessionId,
  228. HttpOnly: false,
  229. }
  230. fmt.Println()
  231. claims := checkAuth(cookie)
  232. fmt.Println(claims)
  233. http.SetCookie(w, cookie)
  234. json.NewEncoder(w).Encode(existUser)
  235. }
  236.  
  237. func getMe(w http.ResponseWriter, r *http.Request) {
  238. cookie, err := r.Cookie("session_id")
  239. fmt.Println(cookie.Path)
  240. if err != nil {
  241. w.Write([]byte("=("))
  242. return
  243. }
  244. claims := checkAuth(cookie)
  245. for _, user := range users {
  246. if user.Nickname == claims["nickname"].(string) {
  247. json.NewEncoder(w).Encode(user)
  248. return
  249. }
  250. }
  251. }
  252.  
  253.  
  254. // ToDO: Add case sensitive ( high/low )
  255. func getUser(w http.ResponseWriter, r *http.Request) {
  256.  
  257. w.Header().Set("Content-Type", "application/json")
  258. params := mux.Vars(r)
  259. for _, item := range users {
  260. //id, _ := strconv.Atoi(params["ID"])
  261. if item.Nickname == params["Nickname"] {
  262. json.NewEncoder(w).Encode(item)
  263. return
  264. }
  265. }
  266. json.NewEncoder(w).Encode(&User{})
  267. }
  268.  
  269.  
  270.  
  271.  
  272.  
  273. func upload(w http.ResponseWriter, r *http.Request) {
  274. r.ParseMultipartForm(32 << 20)
  275. file, _, err := r.FormFile("uploadfile")
  276. if err != nil {
  277. fmt.Println(err)
  278. return
  279. }
  280. defer file.Close()
  281. f, err := os.OpenFile("./static/img/"+"test1.jpg", os.O_WRONLY|os.O_CREATE, 0666) // ToDo: Change way to handle img
  282. if err != nil {
  283. fmt.Println(err)
  284. return
  285. }
  286. defer f.Close()
  287. io.Copy(f, file)
  288. }
  289.  
  290. func main() {
  291. // Mocked part for leaderboard
  292. var mockedUser = User{"1", "evv", "onetaker@gmail.com",
  293. "evv", -100, 23, "test",
  294. "Voronezh", "В левой руке салам"}
  295. var mockedUser1 = User{"2", "tony", "trendpusher@hydra.com",
  296. "qwerty", 100, 22, "test",
  297. "Moscow", "В правой алейкум"}
  298. // Mocker part end
  299. users = append(users, mockedUser)
  300. users = append(users, mockedUser1)
  301. reciever := mux.NewRouter()
  302. // GET ( get exists data )
  303. reciever.HandleFunc("/users/{Nickname}", getUser).Methods("GET")
  304. reciever.HandleFunc("/users/me", getMe).Methods("GET")
  305. reciever.HandleFunc("/leaderboard", getLeaderboard).Methods("GET")
  306. reciever.HandleFunc("/isauth", isAuth).Methods("GET")
  307. //reciever.HandleFunc("/edit", editUser).Methods("GET")
  308.  
  309. // POST ( create new data )
  310. reciever.HandleFunc("/signup", createUser).Methods("POST")
  311. reciever.HandleFunc("/upload", upload).Methods("POST")
  312. reciever.HandleFunc("/login", login).Methods("POST")
  313. reciever.HandleFunc("/users/{Nickname}", editUser).Methods("POST")
  314.  
  315. reciever.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/"))) // Uncomment if want to run locally
  316. log.Fatal(http.ListenAndServe(":8080", reciever))
  317. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement