aboutsummaryrefslogtreecommitdiffstats
path: root/models/user/external_login_user.go
blob: 0e764efb9feefbb45ac86062e6287c1590b94e29 (plain)
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
// Copyright 2017 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package user

import (
	"context"
	"fmt"
	"time"

	"code.gitea.io/gitea/models/db"
	"code.gitea.io/gitea/modules/util"

	"xorm.io/builder"
)

// ErrExternalLoginUserAlreadyExist represents a "ExternalLoginUserAlreadyExist" kind of error.
type ErrExternalLoginUserAlreadyExist struct {
	ExternalID    string
	UserID        int64
	LoginSourceID int64
}

// IsErrExternalLoginUserAlreadyExist checks if an error is a ExternalLoginUserAlreadyExist.
func IsErrExternalLoginUserAlreadyExist(err error) bool {
	_, ok := err.(ErrExternalLoginUserAlreadyExist)
	return ok
}

func (err ErrExternalLoginUserAlreadyExist) Error() string {
	return fmt.Sprintf("external login user already exists [externalID: %s, userID: %d, loginSourceID: %d]", err.ExternalID, err.UserID, err.LoginSourceID)
}

func (err ErrExternalLoginUserAlreadyExist) Unwrap() error {
	return util.ErrAlreadyExist
}

// ErrExternalLoginUserNotExist represents a "ExternalLoginUserNotExist" kind of error.
type ErrExternalLoginUserNotExist struct {
	UserID        int64
	LoginSourceID int64
}

// IsErrExternalLoginUserNotExist checks if an error is a ExternalLoginUserNotExist.
func IsErrExternalLoginUserNotExist(err error) bool {
	_, ok := err.(ErrExternalLoginUserNotExist)
	return ok
}

func (err ErrExternalLoginUserNotExist) Error() string {
	return fmt.Sprintf("external login user link does not exists [userID: %d, loginSourceID: %d]", err.UserID, err.LoginSourceID)
}

func (err ErrExternalLoginUserNotExist) Unwrap() error {
	return util.ErrNotExist
}

// ExternalLoginUser makes the connecting between some existing user and additional external login sources
type ExternalLoginUser struct {
	ExternalID        string         `xorm:"pk NOT NULL"`
	UserID            int64          `xorm:"INDEX NOT NULL"`
	LoginSourceID     int64          `xorm:"pk NOT NULL"`
	RawData           map[string]any `xorm:"TEXT JSON"`
	Provider          string         `xorm:"index VARCHAR(25)"`
	Email             string
	Name              string
	FirstName         string
	LastName          string
	NickName          string
	Description       string
	AvatarURL         string `xorm:"TEXT"`
	Location          string
	AccessToken       string `xorm:"TEXT"`
	AccessTokenSecret string `xorm:"TEXT"`
	RefreshToken      string `xorm:"TEXT"`
	ExpiresAt         time.Time
}

type ExternalUserMigrated interface {
	GetExternalName() string
	GetExternalID() int64
}

type ExternalUserRemappable interface {
	GetUserID() int64
	RemapExternalUser(externalName string, externalID, userID int64) error
	ExternalUserMigrated
}

func init() {
	db.RegisterModel(new(ExternalLoginUser))
}

// GetExternalLogin checks if a externalID in loginSourceID scope already exists
func GetExternalLogin(ctx context.Context, externalLoginUser *ExternalLoginUser) (bool, error) {
	return db.GetEngine(ctx).Get(externalLoginUser)
}

// LinkExternalToUser link the external user to the user
func LinkExternalToUser(ctx context.Context, user *User, externalLoginUser *ExternalLoginUser) error {
	has, err := db.Exist[ExternalLoginUser](ctx, builder.Eq{
		"external_id":     externalLoginUser.ExternalID,
		"login_source_id": externalLoginUser.LoginSourceID,
	})
	if err != nil {
		return err
	} else if has {
		return ErrExternalLoginUserAlreadyExist{externalLoginUser.ExternalID, user.ID, externalLoginUser.LoginSourceID}
	}

	_, err = db.GetEngine(ctx).Insert(externalLoginUser)
	return err
}

// RemoveAccountLink will remove all external login sources for the given user
func RemoveAccountLink(ctx context.Context, user *User, loginSourceID int64) (int64, error) {
	deleted, err := db.GetEngine(ctx).Delete(&ExternalLoginUser{UserID: user.ID, LoginSourceID: loginSourceID})
	if err != nil {
		return deleted, err
	}
	if deleted < 1 {
		return deleted, ErrExternalLoginUserNotExist{user.ID, loginSourceID}
	}
	return deleted, err
}

// RemoveAllAccountLinks will remove all external login sources for the given user
func RemoveAllAccountLinks(ctx context.Context, user *User) error {
	_, err := db.GetEngine(ctx).Delete(&ExternalLoginUser{UserID: user.ID})
	return err
}

// GetUserIDByExternalUserID get user id according to provider and userID
func GetUserIDByExternalUserID(ctx context.Context, provider, userID string) (int64, error) {
	var id int64
	_, err := db.GetEngine(ctx).Table("external_login_user").
		Select("user_id").
		Where("provider=?", provider).
		And("external_id=?", userID).
		Get(&id)
	if err != nil {
		return 0, err
	}
	return id, nil
}

// UpdateExternalUserByExternalID updates an external user's information
func UpdateExternalUserByExternalID(ctx context.Context, external *ExternalLoginUser) error {
	has, err := db.Exist[ExternalLoginUser](ctx, builder.Eq{
		"external_id":     external.ExternalID,
		"login_source_id": external.LoginSourceID,
	})
	if err != nil {
		return err
	} else if !has {
		return ErrExternalLoginUserNotExist{external.UserID, external.LoginSourceID}
	}

	_, err = db.GetEngine(ctx).Where("external_id=? AND login_source_id=?", external.ExternalID, external.LoginSourceID).AllCols().Update(external)
	return err
}

// EnsureLinkExternalToUser link the external user to the user
func EnsureLinkExternalToUser(ctx context.Context, external *ExternalLoginUser) error {
	has, err := db.Exist[ExternalLoginUser](ctx, builder.Eq{
		"external_id":     external.ExternalID,
		"login_source_id": external.LoginSourceID,
	})
	if err != nil {
		return err
	}

	if has {
		_, err = db.GetEngine(ctx).Where("external_id=? AND login_source_id=?", external.ExternalID, external.LoginSourceID).AllCols().Update(external)
		return err
	}

	_, err = db.GetEngine(ctx).Insert(external)
	return err
}

// FindExternalUserOptions represents an options to find external users
type FindExternalUserOptions struct {
	db.ListOptions
	Provider        string
	UserID          int64
	LoginSourceID   int64
	HasRefreshToken bool
	Expired         bool
	OrderBy         string
}

func (opts FindExternalUserOptions) ToConds() builder.Cond {
	cond := builder.NewCond()
	if len(opts.Provider) > 0 {
		cond = cond.And(builder.Eq{"provider": opts.Provider})
	}
	if opts.UserID > 0 {
		cond = cond.And(builder.Eq{"user_id": opts.UserID})
	}
	if opts.Expired {
		cond = cond.And(builder.Lt{"expires_at": time.Now()})
	}
	if opts.HasRefreshToken {
		cond = cond.And(builder.Neq{"refresh_token": ""})
	}
	if opts.LoginSourceID != 0 {
		cond = cond.And(builder.Eq{"login_source_id": opts.LoginSourceID})
	}
	return cond
}

func (opts FindExternalUserOptions) ToOrders() string {
	return opts.OrderBy
}

func IterateExternalLogin(ctx context.Context, opts FindExternalUserOptions, f func(ctx context.Context, u *ExternalLoginUser) error) error {
	return db.Iterate(ctx, opts.ToConds(), f)
}