-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect_session.go
More file actions
60 lines (50 loc) · 1.58 KB
/
Copy pathselect_session.go
File metadata and controls
60 lines (50 loc) · 1.58 KB
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
package main
import (
"database/sql"
"fmt"
"net/http"
"strconv"
"github.com/bafto/FindFavouriteSong/db"
"github.com/gin-gonic/gin"
)
func selectSessionHandler(c *gin.Context) {
logger, user, tx, queries, err := getLoggerUserTransactionQueries(c)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
defer tx.Rollback()
if user.CurrentSession.Valid {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("user already has session"))
return
}
// parse playlist url
sessionIdQuery := c.Query("session_id")
logger.Debug("User selected session", "session-id", sessionIdQuery)
sessionId, err := strconv.Atoi(sessionIdQuery)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("session id must be a valid number"))
return
}
session, err := queries.GetSession(c, int64(sessionId))
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("session does not exist"))
return
}
if session.User != user.ID {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("session does not belong to user"))
return
}
if err := queries.SetUserSession(c, db.SetUserSessionParams{
CurrentSession: sql.NullInt64{Int64: int64(sessionId), Valid: true},
ID: user.ID,
}); err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("failed to set user session: %w", err))
return
}
if err := tx.Commit(); err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("failed to commit DB transaction: %w", err))
return
}
user.CurrentSession = sql.NullInt64{Int64: int64(sessionId), Valid: true}
}