@@ -33,41 +33,44 @@ func CreateUserWithTwitchAccount(t *pg.Tx, user *userv1Model.User) error {
3333 return err
3434}
3535
36+ // Idempotent single transaction method that will:
37+ // 1. Find user in database by the given twitchId
38+ // 2. If missing user will be created accorind to the given user model
39+ // 3. Refresh stored oauth Twitch tokens by revoking old tokens, request new tokens, and save them
40+ // 4. Update the Twitch account record in database if changed according to twitch account model
41+ // 5. Update the last login timestamp for user model
3642func UpsertUserByTwitchId (user * userv1Model.User , twitchId string ) error {
3743 return db .DB ().RunInTransaction (context .Background (), func (tx * pg.Tx ) error {
3844 var foundUser userv1Model.User
39- if err := GetUserByTwitchId (& foundUser , twitchId ); err != nil {
45+ if err := GetUserByTwitchId (tx , & foundUser , twitchId ); err != nil {
4046 if err == pg .ErrNoRows {
4147 return CreateUserWithTwitchAccount (tx , user )
4248 }
4349 return err
4450 }
4551
46- if foundUser .TwitchAccount != nil {
47- go RevokeOldTwitchTokens (* foundUser .TwitchAccount )
48- }
52+ go RevokeOldTwitchTokens (* foundUser .TwitchAccount )
4953
50- if user . TwitchAccount . HasChanged ( foundUser . TwitchAccount ) {
51- if err := UpdateTwitchAccount ( tx , user .TwitchAccount ); err != nil {
52- return err
53- }
54- } else {
55- if err := UpdateTwitchAccountTokens ( tx , user . TwitchAccount ); err != nil {
56- return err
57- }
54+ // replace stored twitch account with newest one
55+ acc := user .TwitchAccount
56+ acc . ID = foundUser . TwitchAccount . ID
57+ * user = foundUser
58+ user . TwitchAccount = acc
59+
60+ if err := UpdateTwitchAccount ( tx , user . TwitchAccount ); err != nil {
61+ return err
5862 }
5963
6064 if err := UpdateLastLogin (tx , user , time .Now ()); err != nil {
6165 return err
6266 }
6367
64- * user = foundUser
6568 return nil
6669 })
6770}
6871
69- func GetUserByTwitchId (user * userv1Model.User , twitchId string ) error {
70- return db . DB () .Model (user ).
72+ func GetUserByTwitchId (tx * pg. Tx , user * userv1Model.User , twitchId string ) error {
73+ return tx .Model (user ).
7174 Relation ("TwitchAccount" ).
7275 Relation ("MCAccount" ).
7376 Where ("twitch_account.twitch_id = ?" , twitchId ).
0 commit comments