manager.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. package user
  2. import (
  3. "database/sql"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. _ "github.com/mattn/go-sqlite3" // SQLite driver
  8. "github.com/stripe/stripe-go/v74"
  9. "golang.org/x/crypto/bcrypt"
  10. "heckel.io/ntfy/log"
  11. "heckel.io/ntfy/util"
  12. "strings"
  13. "sync"
  14. "time"
  15. )
  16. const (
  17. tierIDPrefix = "ti_"
  18. tierIDLength = 8
  19. syncTopicPrefix = "st_"
  20. syncTopicLength = 16
  21. userIDPrefix = "u_"
  22. userIDLength = 12
  23. userPasswordBcryptCost = 10
  24. userAuthIntentionalSlowDownHash = "$2a$10$YFCQvqQDwIIwnJM1xkAYOeih0dg17UVGanaTStnrSzC8NCWxcLDwy" // Cost should match userPasswordBcryptCost
  25. userStatsQueueWriterInterval = 33 * time.Second
  26. userHardDeleteAfterDuration = 7 * 24 * time.Hour
  27. tokenPrefix = "tk_"
  28. tokenLength = 32
  29. tokenMaxCount = 10 // Only keep this many tokens in the table per user
  30. tokenExpiryDuration = 72 * time.Hour // Extend tokens by this much
  31. )
  32. var (
  33. errNoTokenProvided = errors.New("no token provided")
  34. errTopicOwnedByOthers = errors.New("topic owned by others")
  35. errNoRows = errors.New("no rows found")
  36. )
  37. // Manager-related queries
  38. const (
  39. createTablesQueriesNoTx = `
  40. CREATE TABLE IF NOT EXISTS tier (
  41. id TEXT PRIMARY KEY,
  42. code TEXT NOT NULL,
  43. name TEXT NOT NULL,
  44. messages_limit INT NOT NULL,
  45. messages_expiry_duration INT NOT NULL,
  46. emails_limit INT NOT NULL,
  47. reservations_limit INT NOT NULL,
  48. attachment_file_size_limit INT NOT NULL,
  49. attachment_total_size_limit INT NOT NULL,
  50. attachment_expiry_duration INT NOT NULL,
  51. attachment_bandwidth_limit INT NOT NULL,
  52. stripe_price_id TEXT
  53. );
  54. CREATE UNIQUE INDEX idx_tier_code ON tier (code);
  55. CREATE UNIQUE INDEX idx_tier_price_id ON tier (stripe_price_id);
  56. CREATE TABLE IF NOT EXISTS user (
  57. id TEXT PRIMARY KEY,
  58. tier_id TEXT,
  59. user TEXT NOT NULL,
  60. pass TEXT NOT NULL,
  61. role TEXT CHECK (role IN ('anonymous', 'admin', 'user')) NOT NULL,
  62. prefs JSON NOT NULL DEFAULT '{}',
  63. sync_topic TEXT NOT NULL,
  64. stats_messages INT NOT NULL DEFAULT (0),
  65. stats_emails INT NOT NULL DEFAULT (0),
  66. stripe_customer_id TEXT,
  67. stripe_subscription_id TEXT,
  68. stripe_subscription_status TEXT,
  69. stripe_subscription_paid_until INT,
  70. stripe_subscription_cancel_at INT,
  71. created INT NOT NULL,
  72. deleted INT,
  73. FOREIGN KEY (tier_id) REFERENCES tier (id)
  74. );
  75. CREATE UNIQUE INDEX idx_user ON user (user);
  76. CREATE UNIQUE INDEX idx_user_stripe_customer_id ON user (stripe_customer_id);
  77. CREATE UNIQUE INDEX idx_user_stripe_subscription_id ON user (stripe_subscription_id);
  78. CREATE TABLE IF NOT EXISTS user_access (
  79. user_id TEXT NOT NULL,
  80. topic TEXT NOT NULL,
  81. read INT NOT NULL,
  82. write INT NOT NULL,
  83. owner_user_id INT,
  84. PRIMARY KEY (user_id, topic),
  85. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE,
  86. FOREIGN KEY (owner_user_id) REFERENCES user (id) ON DELETE CASCADE
  87. );
  88. CREATE TABLE IF NOT EXISTS user_token (
  89. user_id TEXT NOT NULL,
  90. token TEXT NOT NULL,
  91. expires INT NOT NULL,
  92. PRIMARY KEY (user_id, token),
  93. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE
  94. );
  95. CREATE TABLE IF NOT EXISTS schemaVersion (
  96. id INT PRIMARY KEY,
  97. version INT NOT NULL
  98. );
  99. INSERT INTO user (id, user, pass, role, sync_topic, created)
  100. VALUES ('` + everyoneID + `', '*', '', 'anonymous', '', UNIXEPOCH())
  101. ON CONFLICT (id) DO NOTHING;
  102. `
  103. createTablesQueries = `BEGIN; ` + createTablesQueriesNoTx + ` COMMIT;`
  104. builtinStartupQueries = `
  105. PRAGMA foreign_keys = ON;
  106. `
  107. selectUserByIDQuery = `
  108. SELECT u.id, u.user, u.pass, u.role, u.prefs, u.sync_topic, u.stats_messages, u.stats_emails, u.stripe_customer_id, u.stripe_subscription_id, u.stripe_subscription_status, u.stripe_subscription_paid_until, u.stripe_subscription_cancel_at, deleted, t.id, t.code, t.name, t.messages_limit, t.messages_expiry_duration, t.emails_limit, t.reservations_limit, t.attachment_file_size_limit, t.attachment_total_size_limit, t.attachment_expiry_duration, t.attachment_bandwidth_limit, t.stripe_price_id
  109. FROM user u
  110. LEFT JOIN tier t on t.id = u.tier_id
  111. WHERE u.id = ?
  112. `
  113. selectUserByNameQuery = `
  114. SELECT u.id, u.user, u.pass, u.role, u.prefs, u.sync_topic, u.stats_messages, u.stats_emails, u.stripe_customer_id, u.stripe_subscription_id, u.stripe_subscription_status, u.stripe_subscription_paid_until, u.stripe_subscription_cancel_at, deleted, t.id, t.code, t.name, t.messages_limit, t.messages_expiry_duration, t.emails_limit, t.reservations_limit, t.attachment_file_size_limit, t.attachment_total_size_limit, t.attachment_expiry_duration, t.attachment_bandwidth_limit, t.stripe_price_id
  115. FROM user u
  116. LEFT JOIN tier t on t.id = u.tier_id
  117. WHERE user = ?
  118. `
  119. selectUserByTokenQuery = `
  120. SELECT u.id, u.user, u.pass, u.role, u.prefs, u.sync_topic, u.stats_messages, u.stats_emails, u.stripe_customer_id, u.stripe_subscription_id, u.stripe_subscription_status, u.stripe_subscription_paid_until, u.stripe_subscription_cancel_at, deleted, t.id, t.code, t.name, t.messages_limit, t.messages_expiry_duration, t.emails_limit, t.reservations_limit, t.attachment_file_size_limit, t.attachment_total_size_limit, t.attachment_expiry_duration, t.attachment_bandwidth_limit, t.stripe_price_id
  121. FROM user u
  122. JOIN user_token t on u.id = t.user_id
  123. LEFT JOIN tier t on t.id = u.tier_id
  124. WHERE t.token = ? AND t.expires >= ?
  125. `
  126. selectUserByStripeCustomerIDQuery = `
  127. SELECT u.id, u.user, u.pass, u.role, u.prefs, u.sync_topic, u.stats_messages, u.stats_emails, u.stripe_customer_id, u.stripe_subscription_id, u.stripe_subscription_status, u.stripe_subscription_paid_until, u.stripe_subscription_cancel_at, deleted, t.id, t.code, t.name, t.messages_limit, t.messages_expiry_duration, t.emails_limit, t.reservations_limit, t.attachment_file_size_limit, t.attachment_total_size_limit, t.attachment_expiry_duration, t.attachment_bandwidth_limit, t.stripe_price_id
  128. FROM user u
  129. LEFT JOIN tier t on t.id = u.tier_id
  130. WHERE u.stripe_customer_id = ?
  131. `
  132. selectTopicPermsQuery = `
  133. SELECT read, write
  134. FROM user_access a
  135. JOIN user u ON u.id = a.user_id
  136. WHERE (u.user = ? OR u.user = ?) AND ? LIKE a.topic
  137. ORDER BY u.user DESC
  138. `
  139. insertUserQuery = `
  140. INSERT INTO user (id, user, pass, role, sync_topic, created)
  141. VALUES (?, ?, ?, ?, ?, ?)
  142. `
  143. selectUsernamesQuery = `
  144. SELECT user
  145. FROM user
  146. ORDER BY
  147. CASE role
  148. WHEN 'admin' THEN 1
  149. WHEN 'anonymous' THEN 3
  150. ELSE 2
  151. END, user
  152. `
  153. updateUserPassQuery = `UPDATE user SET pass = ? WHERE user = ?`
  154. updateUserRoleQuery = `UPDATE user SET role = ? WHERE user = ?`
  155. updateUserPrefsQuery = `UPDATE user SET prefs = ? WHERE user = ?`
  156. updateUserStatsQuery = `UPDATE user SET stats_messages = ?, stats_emails = ? WHERE id = ?`
  157. updateUserStatsResetAllQuery = `UPDATE user SET stats_messages = 0, stats_emails = 0`
  158. updateUserDeletedQuery = `UPDATE user SET deleted = ? WHERE id = ?`
  159. deleteUsersMarkedQuery = `DELETE FROM user WHERE deleted < ?`
  160. deleteUserQuery = `DELETE FROM user WHERE user = ?`
  161. upsertUserAccessQuery = `
  162. INSERT INTO user_access (user_id, topic, read, write, owner_user_id)
  163. VALUES ((SELECT id FROM user WHERE user = ?), ?, ?, ?, (SELECT IIF(?='',NULL,(SELECT id FROM user WHERE user=?))))
  164. ON CONFLICT (user_id, topic)
  165. DO UPDATE SET read=excluded.read, write=excluded.write, owner_user_id=excluded.owner_user_id
  166. `
  167. selectUserAccessQuery = `
  168. SELECT topic, read, write
  169. FROM user_access
  170. WHERE user_id = (SELECT id FROM user WHERE user = ?)
  171. ORDER BY write DESC, read DESC, topic
  172. `
  173. selectUserReservationsQuery = `
  174. SELECT a_user.topic, a_user.read, a_user.write, a_everyone.read AS everyone_read, a_everyone.write AS everyone_write
  175. FROM user_access a_user
  176. LEFT JOIN user_access a_everyone ON a_user.topic = a_everyone.topic AND a_everyone.user_id = (SELECT id FROM user WHERE user = ?)
  177. WHERE a_user.user_id = a_user.owner_user_id
  178. AND a_user.owner_user_id = (SELECT id FROM user WHERE user = ?)
  179. ORDER BY a_user.topic
  180. `
  181. selectUserReservationsCountQuery = `
  182. SELECT COUNT(*)
  183. FROM user_access
  184. WHERE user_id = owner_user_id AND owner_user_id = (SELECT id FROM user WHERE user = ?)
  185. `
  186. selectUserHasReservationQuery = `
  187. SELECT COUNT(*)
  188. FROM user_access
  189. WHERE user_id = owner_user_id
  190. AND owner_user_id = (SELECT id FROM user WHERE user = ?)
  191. AND topic = ?
  192. `
  193. selectOtherAccessCountQuery = `
  194. SELECT COUNT(*)
  195. FROM user_access
  196. WHERE (topic = ? OR ? LIKE topic)
  197. AND (owner_user_id IS NULL OR owner_user_id != (SELECT id FROM user WHERE user = ?))
  198. `
  199. deleteAllAccessQuery = `DELETE FROM user_access`
  200. deleteUserAccessQuery = `
  201. DELETE FROM user_access
  202. WHERE user_id = (SELECT id FROM user WHERE user = ?)
  203. OR owner_user_id = (SELECT id FROM user WHERE user = ?)
  204. `
  205. deleteTopicAccessQuery = `
  206. DELETE FROM user_access
  207. WHERE (user_id = (SELECT id FROM user WHERE user = ?) OR owner_user_id = (SELECT id FROM user WHERE user = ?))
  208. AND topic = ?
  209. `
  210. selectTokenCountQuery = `SELECT COUNT(*) FROM user_token WHERE user_id = ?`
  211. insertTokenQuery = `INSERT INTO user_token (user_id, token, expires) VALUES (?, ?, ?)`
  212. updateTokenExpiryQuery = `UPDATE user_token SET expires = ? WHERE user_id = (SELECT id FROM user WHERE user = ?) AND token = ?`
  213. deleteTokenQuery = `DELETE FROM user_token WHERE user_id = ? AND token = ?`
  214. deleteAllTokenQuery = `DELETE FROM user_token WHERE user_id = ?`
  215. deleteExpiredTokensQuery = `DELETE FROM user_token WHERE expires < ?`
  216. deleteExcessTokensQuery = `
  217. DELETE FROM user_token
  218. WHERE (user_id, token) NOT IN (
  219. SELECT user_id, token
  220. FROM user_token
  221. WHERE user_id = ?
  222. ORDER BY expires DESC
  223. LIMIT ?
  224. )
  225. `
  226. insertTierQuery = `
  227. INSERT INTO tier (id, code, name, messages_limit, messages_expiry_duration, emails_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_price_id)
  228. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  229. `
  230. selectTiersQuery = `
  231. SELECT id, code, name, messages_limit, messages_expiry_duration, emails_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_price_id
  232. FROM tier
  233. `
  234. selectTierByCodeQuery = `
  235. SELECT id, code, name, messages_limit, messages_expiry_duration, emails_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_price_id
  236. FROM tier
  237. WHERE code = ?
  238. `
  239. selectTierByPriceIDQuery = `
  240. SELECT id, code, name, messages_limit, messages_expiry_duration, emails_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_price_id
  241. FROM tier
  242. WHERE stripe_price_id = ?
  243. `
  244. updateUserTierQuery = `UPDATE user SET tier_id = (SELECT id FROM tier WHERE code = ?) WHERE user = ?`
  245. deleteUserTierQuery = `UPDATE user SET tier_id = null WHERE user = ?`
  246. updateBillingQuery = `
  247. UPDATE user
  248. SET stripe_customer_id = ?, stripe_subscription_id = ?, stripe_subscription_status = ?, stripe_subscription_paid_until = ?, stripe_subscription_cancel_at = ?
  249. WHERE user = ?
  250. `
  251. )
  252. // Schema management queries
  253. const (
  254. currentSchemaVersion = 2
  255. insertSchemaVersion = `INSERT INTO schemaVersion VALUES (1, ?)`
  256. updateSchemaVersion = `UPDATE schemaVersion SET version = ? WHERE id = 1`
  257. selectSchemaVersionQuery = `SELECT version FROM schemaVersion WHERE id = 1`
  258. // 1 -> 2 (complex migration!)
  259. migrate1To2RenameUserTableQueryNoTx = `
  260. ALTER TABLE user RENAME TO user_old;
  261. `
  262. migrate1To2SelectAllOldUsernamesNoTx = `SELECT user FROM user_old`
  263. migrate1To2InsertUserNoTx = `
  264. INSERT INTO user (id, user, pass, role, sync_topic, created)
  265. SELECT ?, user, pass, role, ?, UNIXEPOCH() FROM user_old WHERE user = ?
  266. `
  267. migrate1To2InsertFromOldTablesAndDropNoTx = `
  268. INSERT INTO user_access (user_id, topic, read, write)
  269. SELECT u.id, a.topic, a.read, a.write
  270. FROM user u
  271. JOIN access a ON u.user = a.user;
  272. DROP TABLE access;
  273. DROP TABLE user_old;
  274. `
  275. migrate1To2UpdateSyncTopicNoTx = `UPDATE user SET sync_topic = ? WHERE id = ?`
  276. )
  277. // Manager is an implementation of Manager. It stores users and access control list
  278. // in a SQLite database.
  279. type Manager struct {
  280. db *sql.DB
  281. defaultAccess Permission // Default permission if no ACL matches
  282. statsQueue map[string]*Stats // "Queue" to asynchronously write user stats to the database (UserID -> Stats)
  283. mu sync.Mutex
  284. }
  285. var _ Auther = (*Manager)(nil)
  286. // NewManager creates a new Manager instance
  287. func NewManager(filename, startupQueries string, defaultAccess Permission) (*Manager, error) {
  288. return NewManagerWithStatsInterval(filename, startupQueries, defaultAccess, userStatsQueueWriterInterval)
  289. }
  290. // NewManagerWithStatsInterval creates a new Manager instance
  291. func NewManagerWithStatsInterval(filename, startupQueries string, defaultAccess Permission, statsWriterInterval time.Duration) (*Manager, error) {
  292. db, err := sql.Open("sqlite3", filename)
  293. if err != nil {
  294. return nil, err
  295. }
  296. if err := setupDB(db); err != nil {
  297. return nil, err
  298. }
  299. if err := runStartupQueries(db, startupQueries); err != nil {
  300. return nil, err
  301. }
  302. manager := &Manager{
  303. db: db,
  304. defaultAccess: defaultAccess,
  305. statsQueue: make(map[string]*Stats),
  306. }
  307. go manager.userStatsQueueWriter(statsWriterInterval)
  308. return manager, nil
  309. }
  310. // Authenticate checks username and password and returns a User if correct, and the user has not been
  311. // marked as deleted. The method returns in constant-ish time, regardless of whether the user exists or
  312. // the password is correct or incorrect.
  313. func (a *Manager) Authenticate(username, password string) (*User, error) {
  314. if username == Everyone {
  315. return nil, ErrUnauthenticated
  316. }
  317. user, err := a.User(username)
  318. if err != nil {
  319. log.Trace("authentication of user %s failed (1): %s", username, err.Error())
  320. bcrypt.CompareHashAndPassword([]byte(userAuthIntentionalSlowDownHash), []byte("intentional slow-down to avoid timing attacks"))
  321. return nil, ErrUnauthenticated
  322. } else if user.Deleted {
  323. log.Trace("authentication of user %s failed (2): user marked deleted", username)
  324. bcrypt.CompareHashAndPassword([]byte(userAuthIntentionalSlowDownHash), []byte("intentional slow-down to avoid timing attacks"))
  325. return nil, ErrUnauthenticated
  326. } else if err := bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(password)); err != nil {
  327. log.Trace("authentication of user %s failed (3): %s", username, err.Error())
  328. return nil, ErrUnauthenticated
  329. }
  330. return user, nil
  331. }
  332. // AuthenticateToken checks if the token exists and returns the associated User if it does.
  333. // The method sets the User.Token value to the token that was used for authentication.
  334. func (a *Manager) AuthenticateToken(token string) (*User, error) {
  335. if len(token) != tokenLength {
  336. return nil, ErrUnauthenticated
  337. }
  338. user, err := a.userByToken(token)
  339. if err != nil {
  340. return nil, ErrUnauthenticated
  341. }
  342. user.Token = token
  343. return user, nil
  344. }
  345. // CreateToken generates a random token for the given user and returns it. The token expires
  346. // after a fixed duration unless ExtendToken is called. This function also prunes tokens for the
  347. // given user, if there are too many of them.
  348. func (a *Manager) CreateToken(user *User) (*Token, error) {
  349. token, expires := util.RandomStringPrefix(tokenPrefix, tokenLength), time.Now().Add(tokenExpiryDuration)
  350. tx, err := a.db.Begin()
  351. if err != nil {
  352. return nil, err
  353. }
  354. defer tx.Rollback()
  355. if _, err := tx.Exec(insertTokenQuery, user.ID, token, expires.Unix()); err != nil {
  356. return nil, err
  357. }
  358. rows, err := tx.Query(selectTokenCountQuery, user.ID)
  359. if err != nil {
  360. return nil, err
  361. }
  362. defer rows.Close()
  363. if !rows.Next() {
  364. return nil, errNoRows
  365. }
  366. var tokenCount int
  367. if err := rows.Scan(&tokenCount); err != nil {
  368. return nil, err
  369. }
  370. if tokenCount >= tokenMaxCount {
  371. // This pruning logic is done in two queries for efficiency. The SELECT above is a lookup
  372. // on two indices, whereas the query below is a full table scan.
  373. if _, err := tx.Exec(deleteExcessTokensQuery, user.ID, tokenMaxCount); err != nil {
  374. return nil, err
  375. }
  376. }
  377. if err := tx.Commit(); err != nil {
  378. return nil, err
  379. }
  380. return &Token{
  381. Value: token,
  382. Expires: expires,
  383. }, nil
  384. }
  385. // ExtendToken sets the new expiry date for a token, thereby extending its use further into the future.
  386. func (a *Manager) ExtendToken(user *User) (*Token, error) {
  387. if user.Token == "" {
  388. return nil, errNoTokenProvided
  389. }
  390. newExpires := time.Now().Add(tokenExpiryDuration)
  391. if _, err := a.db.Exec(updateTokenExpiryQuery, newExpires.Unix(), user.Name, user.Token); err != nil {
  392. return nil, err
  393. }
  394. return &Token{
  395. Value: user.Token,
  396. Expires: newExpires,
  397. }, nil
  398. }
  399. // RemoveToken deletes the token defined in User.Token
  400. func (a *Manager) RemoveToken(user *User) error {
  401. if user.Token == "" {
  402. return ErrUnauthorized
  403. }
  404. if _, err := a.db.Exec(deleteTokenQuery, user.ID, user.Token); err != nil {
  405. return err
  406. }
  407. return nil
  408. }
  409. // RemoveExpiredTokens deletes all expired tokens from the database
  410. func (a *Manager) RemoveExpiredTokens() error {
  411. if _, err := a.db.Exec(deleteExpiredTokensQuery, time.Now().Unix()); err != nil {
  412. return err
  413. }
  414. return nil
  415. }
  416. // RemoveDeletedUsers deletes all users that have been marked deleted for
  417. func (a *Manager) RemoveDeletedUsers() error {
  418. if _, err := a.db.Exec(deleteUsersMarkedQuery, time.Now().Unix()); err != nil {
  419. return err
  420. }
  421. return nil
  422. }
  423. // ChangeSettings persists the user settings
  424. func (a *Manager) ChangeSettings(user *User) error {
  425. prefs, err := json.Marshal(user.Prefs)
  426. if err != nil {
  427. return err
  428. }
  429. if _, err := a.db.Exec(updateUserPrefsQuery, string(prefs), user.Name); err != nil {
  430. return err
  431. }
  432. return nil
  433. }
  434. // ResetStats resets all user stats in the user database. This touches all users.
  435. func (a *Manager) ResetStats() error {
  436. a.mu.Lock()
  437. defer a.mu.Unlock()
  438. if _, err := a.db.Exec(updateUserStatsResetAllQuery); err != nil {
  439. return err
  440. }
  441. a.statsQueue = make(map[string]*Stats)
  442. return nil
  443. }
  444. // EnqueueStats adds the user to a queue which writes out user stats (messages, emails, ..) in
  445. // batches at a regular interval
  446. func (a *Manager) EnqueueStats(userID string, stats *Stats) {
  447. a.mu.Lock()
  448. defer a.mu.Unlock()
  449. a.statsQueue[userID] = stats
  450. }
  451. func (a *Manager) userStatsQueueWriter(interval time.Duration) {
  452. ticker := time.NewTicker(interval)
  453. for range ticker.C {
  454. if err := a.writeUserStatsQueue(); err != nil {
  455. log.Warn("User Manager: Writing user stats queue failed: %s", err.Error())
  456. }
  457. }
  458. }
  459. func (a *Manager) writeUserStatsQueue() error {
  460. a.mu.Lock()
  461. if len(a.statsQueue) == 0 {
  462. a.mu.Unlock()
  463. log.Trace("User Manager: No user stats updates to commit")
  464. return nil
  465. }
  466. statsQueue := a.statsQueue
  467. a.statsQueue = make(map[string]*Stats)
  468. a.mu.Unlock()
  469. tx, err := a.db.Begin()
  470. if err != nil {
  471. return err
  472. }
  473. defer tx.Rollback()
  474. log.Debug("User Manager: Writing user stats queue for %d user(s)", len(statsQueue))
  475. for userID, update := range statsQueue {
  476. log.Trace("User Manager: Updating stats for user %s: messages=%d, emails=%d", userID, update.Messages, update.Emails)
  477. if _, err := tx.Exec(updateUserStatsQuery, update.Messages, update.Emails, userID); err != nil {
  478. return err
  479. }
  480. }
  481. return tx.Commit()
  482. }
  483. // Authorize returns nil if the given user has access to the given topic using the desired
  484. // permission. The user param may be nil to signal an anonymous user.
  485. func (a *Manager) Authorize(user *User, topic string, perm Permission) error {
  486. if user != nil && user.Role == RoleAdmin {
  487. return nil // Admin can do everything
  488. }
  489. username := Everyone
  490. if user != nil {
  491. username = user.Name
  492. }
  493. // Select the read/write permissions for this user/topic combo. The query may return two
  494. // rows (one for everyone, and one for the user), but prioritizes the user.
  495. rows, err := a.db.Query(selectTopicPermsQuery, Everyone, username, topic)
  496. if err != nil {
  497. return err
  498. }
  499. defer rows.Close()
  500. if !rows.Next() {
  501. return a.resolvePerms(a.defaultAccess, perm)
  502. }
  503. var read, write bool
  504. if err := rows.Scan(&read, &write); err != nil {
  505. return err
  506. } else if err := rows.Err(); err != nil {
  507. return err
  508. }
  509. return a.resolvePerms(NewPermission(read, write), perm)
  510. }
  511. func (a *Manager) resolvePerms(base, perm Permission) error {
  512. if perm == PermissionRead && base.IsRead() {
  513. return nil
  514. } else if perm == PermissionWrite && base.IsWrite() {
  515. return nil
  516. }
  517. return ErrUnauthorized
  518. }
  519. // AddUser adds a user with the given username, password and role
  520. func (a *Manager) AddUser(username, password string, role Role) error {
  521. if !AllowedUsername(username) || !AllowedRole(role) {
  522. return ErrInvalidArgument
  523. }
  524. hash, err := bcrypt.GenerateFromPassword([]byte(password), userPasswordBcryptCost)
  525. if err != nil {
  526. return err
  527. }
  528. userID := util.RandomStringPrefix(userIDPrefix, userIDLength)
  529. syncTopic, now := util.RandomStringPrefix(syncTopicPrefix, syncTopicLength), time.Now().Unix()
  530. if _, err = a.db.Exec(insertUserQuery, userID, username, hash, role, syncTopic, now); err != nil {
  531. return err
  532. }
  533. return nil
  534. }
  535. // RemoveUser deletes the user with the given username. The function returns nil on success, even
  536. // if the user did not exist in the first place.
  537. func (a *Manager) RemoveUser(username string) error {
  538. if !AllowedUsername(username) {
  539. return ErrInvalidArgument
  540. }
  541. // Rows in user_access, user_token, etc. are deleted via foreign keys
  542. if _, err := a.db.Exec(deleteUserQuery, username); err != nil {
  543. return err
  544. }
  545. return nil
  546. }
  547. // MarkUserRemoved sets the deleted flag on the user, and deletes all access tokens. This prevents
  548. // successful auth via Authenticate. A background process will delete the user at a later date.
  549. func (a *Manager) MarkUserRemoved(user *User) error {
  550. if !AllowedUsername(user.Name) {
  551. return ErrInvalidArgument
  552. }
  553. tx, err := a.db.Begin()
  554. if err != nil {
  555. return err
  556. }
  557. defer tx.Rollback()
  558. if _, err := a.db.Exec(deleteUserAccessQuery, user.Name, user.Name); err != nil {
  559. return err
  560. }
  561. if _, err := tx.Exec(deleteAllTokenQuery, user.ID); err != nil {
  562. return err
  563. }
  564. if _, err := tx.Exec(updateUserDeletedQuery, time.Now().Add(userHardDeleteAfterDuration).Unix(), user.ID); err != nil {
  565. return err
  566. }
  567. return tx.Commit()
  568. }
  569. // Users returns a list of users. It always also returns the Everyone user ("*").
  570. func (a *Manager) Users() ([]*User, error) {
  571. rows, err := a.db.Query(selectUsernamesQuery)
  572. if err != nil {
  573. return nil, err
  574. }
  575. defer rows.Close()
  576. usernames := make([]string, 0)
  577. for rows.Next() {
  578. var username string
  579. if err := rows.Scan(&username); err != nil {
  580. return nil, err
  581. } else if err := rows.Err(); err != nil {
  582. return nil, err
  583. }
  584. usernames = append(usernames, username)
  585. }
  586. rows.Close()
  587. users := make([]*User, 0)
  588. for _, username := range usernames {
  589. user, err := a.User(username)
  590. if err != nil {
  591. return nil, err
  592. }
  593. users = append(users, user)
  594. }
  595. return users, nil
  596. }
  597. // User returns the user with the given username if it exists, or ErrUserNotFound otherwise.
  598. // You may also pass Everyone to retrieve the anonymous user and its Grant list.
  599. func (a *Manager) User(username string) (*User, error) {
  600. rows, err := a.db.Query(selectUserByNameQuery, username)
  601. if err != nil {
  602. return nil, err
  603. }
  604. return a.readUser(rows)
  605. }
  606. // UserByID returns the user with the given ID if it exists, or ErrUserNotFound otherwise
  607. func (a *Manager) UserByID(id string) (*User, error) {
  608. rows, err := a.db.Query(selectUserByIDQuery, id)
  609. if err != nil {
  610. return nil, err
  611. }
  612. return a.readUser(rows)
  613. }
  614. // UserByStripeCustomer returns the user with the given Stripe customer ID if it exists, or ErrUserNotFound otherwise.
  615. func (a *Manager) UserByStripeCustomer(stripeCustomerID string) (*User, error) {
  616. rows, err := a.db.Query(selectUserByStripeCustomerIDQuery, stripeCustomerID)
  617. if err != nil {
  618. return nil, err
  619. }
  620. return a.readUser(rows)
  621. }
  622. func (a *Manager) userByToken(token string) (*User, error) {
  623. rows, err := a.db.Query(selectUserByTokenQuery, token, time.Now().Unix())
  624. if err != nil {
  625. return nil, err
  626. }
  627. return a.readUser(rows)
  628. }
  629. func (a *Manager) readUser(rows *sql.Rows) (*User, error) {
  630. defer rows.Close()
  631. var id, username, hash, role, prefs, syncTopic string
  632. var stripeCustomerID, stripeSubscriptionID, stripeSubscriptionStatus, stripePriceID, tierID, tierCode, tierName sql.NullString
  633. var messages, emails int64
  634. var messagesLimit, messagesExpiryDuration, emailsLimit, reservationsLimit, attachmentFileSizeLimit, attachmentTotalSizeLimit, attachmentExpiryDuration, attachmentBandwidthLimit, stripeSubscriptionPaidUntil, stripeSubscriptionCancelAt, deleted sql.NullInt64
  635. if !rows.Next() {
  636. return nil, ErrUserNotFound
  637. }
  638. if err := rows.Scan(&id, &username, &hash, &role, &prefs, &syncTopic, &messages, &emails, &stripeCustomerID, &stripeSubscriptionID, &stripeSubscriptionStatus, &stripeSubscriptionPaidUntil, &stripeSubscriptionCancelAt, &deleted, &tierID, &tierCode, &tierName, &messagesLimit, &messagesExpiryDuration, &emailsLimit, &reservationsLimit, &attachmentFileSizeLimit, &attachmentTotalSizeLimit, &attachmentExpiryDuration, &attachmentBandwidthLimit, &stripePriceID); err != nil {
  639. return nil, err
  640. } else if err := rows.Err(); err != nil {
  641. return nil, err
  642. }
  643. user := &User{
  644. ID: id,
  645. Name: username,
  646. Hash: hash,
  647. Role: Role(role),
  648. Prefs: &Prefs{},
  649. SyncTopic: syncTopic,
  650. Stats: &Stats{
  651. Messages: messages,
  652. Emails: emails,
  653. },
  654. Billing: &Billing{
  655. StripeCustomerID: stripeCustomerID.String, // May be empty
  656. StripeSubscriptionID: stripeSubscriptionID.String, // May be empty
  657. StripeSubscriptionStatus: stripe.SubscriptionStatus(stripeSubscriptionStatus.String), // May be empty
  658. StripeSubscriptionPaidUntil: time.Unix(stripeSubscriptionPaidUntil.Int64, 0), // May be zero
  659. StripeSubscriptionCancelAt: time.Unix(stripeSubscriptionCancelAt.Int64, 0), // May be zero
  660. },
  661. Deleted: deleted.Valid,
  662. }
  663. if err := json.Unmarshal([]byte(prefs), user.Prefs); err != nil {
  664. return nil, err
  665. }
  666. if tierCode.Valid {
  667. // See readTier() when this is changed!
  668. user.Tier = &Tier{
  669. ID: tierID.String,
  670. Code: tierCode.String,
  671. Name: tierName.String,
  672. MessageLimit: messagesLimit.Int64,
  673. MessageExpiryDuration: time.Duration(messagesExpiryDuration.Int64) * time.Second,
  674. EmailLimit: emailsLimit.Int64,
  675. ReservationLimit: reservationsLimit.Int64,
  676. AttachmentFileSizeLimit: attachmentFileSizeLimit.Int64,
  677. AttachmentTotalSizeLimit: attachmentTotalSizeLimit.Int64,
  678. AttachmentExpiryDuration: time.Duration(attachmentExpiryDuration.Int64) * time.Second,
  679. AttachmentBandwidthLimit: attachmentBandwidthLimit.Int64,
  680. StripePriceID: stripePriceID.String, // May be empty
  681. }
  682. }
  683. return user, nil
  684. }
  685. // Grants returns all user-specific access control entries
  686. func (a *Manager) Grants(username string) ([]Grant, error) {
  687. rows, err := a.db.Query(selectUserAccessQuery, username)
  688. if err != nil {
  689. return nil, err
  690. }
  691. defer rows.Close()
  692. grants := make([]Grant, 0)
  693. for rows.Next() {
  694. var topic string
  695. var read, write bool
  696. if err := rows.Scan(&topic, &read, &write); err != nil {
  697. return nil, err
  698. } else if err := rows.Err(); err != nil {
  699. return nil, err
  700. }
  701. grants = append(grants, Grant{
  702. TopicPattern: fromSQLWildcard(topic),
  703. Allow: NewPermission(read, write),
  704. })
  705. }
  706. return grants, nil
  707. }
  708. // Reservations returns all user-owned topics, and the associated everyone-access
  709. func (a *Manager) Reservations(username string) ([]Reservation, error) {
  710. rows, err := a.db.Query(selectUserReservationsQuery, Everyone, username)
  711. if err != nil {
  712. return nil, err
  713. }
  714. defer rows.Close()
  715. reservations := make([]Reservation, 0)
  716. for rows.Next() {
  717. var topic string
  718. var ownerRead, ownerWrite bool
  719. var everyoneRead, everyoneWrite sql.NullBool
  720. if err := rows.Scan(&topic, &ownerRead, &ownerWrite, &everyoneRead, &everyoneWrite); err != nil {
  721. return nil, err
  722. } else if err := rows.Err(); err != nil {
  723. return nil, err
  724. }
  725. reservations = append(reservations, Reservation{
  726. Topic: topic,
  727. Owner: NewPermission(ownerRead, ownerWrite),
  728. Everyone: NewPermission(everyoneRead.Bool, everyoneWrite.Bool), // false if null
  729. })
  730. }
  731. return reservations, nil
  732. }
  733. // HasReservation returns true if the given topic access is owned by the user
  734. func (a *Manager) HasReservation(username, topic string) (bool, error) {
  735. rows, err := a.db.Query(selectUserHasReservationQuery, username, topic)
  736. if err != nil {
  737. return false, err
  738. }
  739. defer rows.Close()
  740. if !rows.Next() {
  741. return false, errNoRows
  742. }
  743. var count int64
  744. if err := rows.Scan(&count); err != nil {
  745. return false, err
  746. }
  747. return count > 0, nil
  748. }
  749. // ReservationsCount returns the number of reservations owned by this user
  750. func (a *Manager) ReservationsCount(username string) (int64, error) {
  751. rows, err := a.db.Query(selectUserReservationsCountQuery, username)
  752. if err != nil {
  753. return 0, err
  754. }
  755. defer rows.Close()
  756. if !rows.Next() {
  757. return 0, errNoRows
  758. }
  759. var count int64
  760. if err := rows.Scan(&count); err != nil {
  761. return 0, err
  762. }
  763. return count, nil
  764. }
  765. // ChangePassword changes a user's password
  766. func (a *Manager) ChangePassword(username, password string) error {
  767. hash, err := bcrypt.GenerateFromPassword([]byte(password), userPasswordBcryptCost)
  768. if err != nil {
  769. return err
  770. }
  771. if _, err := a.db.Exec(updateUserPassQuery, hash, username); err != nil {
  772. return err
  773. }
  774. return nil
  775. }
  776. // ChangeRole changes a user's role. When a role is changed from RoleUser to RoleAdmin,
  777. // all existing access control entries (Grant) are removed, since they are no longer needed.
  778. func (a *Manager) ChangeRole(username string, role Role) error {
  779. if !AllowedUsername(username) || !AllowedRole(role) {
  780. return ErrInvalidArgument
  781. }
  782. if _, err := a.db.Exec(updateUserRoleQuery, string(role), username); err != nil {
  783. return err
  784. }
  785. if role == RoleAdmin {
  786. if _, err := a.db.Exec(deleteUserAccessQuery, username, username); err != nil {
  787. return err
  788. }
  789. }
  790. return nil
  791. }
  792. // ChangeTier changes a user's tier using the tier code. This function does not delete reservations, messages,
  793. // or attachments, even if the new tier has lower limits in this regard. That has to be done elsewhere.
  794. func (a *Manager) ChangeTier(username, tier string) error {
  795. if !AllowedUsername(username) {
  796. return ErrInvalidArgument
  797. }
  798. t, err := a.Tier(tier)
  799. if err != nil {
  800. return err
  801. } else if err := a.checkReservationsLimit(username, t.ReservationLimit); err != nil {
  802. return err
  803. }
  804. if _, err := a.db.Exec(updateUserTierQuery, tier, username); err != nil {
  805. return err
  806. }
  807. return nil
  808. }
  809. // ResetTier removes the tier from the given user
  810. func (a *Manager) ResetTier(username string) error {
  811. if !AllowedUsername(username) && username != Everyone && username != "" {
  812. return ErrInvalidArgument
  813. } else if err := a.checkReservationsLimit(username, 0); err != nil {
  814. return err
  815. }
  816. _, err := a.db.Exec(deleteUserTierQuery, username)
  817. return err
  818. }
  819. func (a *Manager) checkReservationsLimit(username string, reservationsLimit int64) error {
  820. u, err := a.User(username)
  821. if err != nil {
  822. return err
  823. }
  824. if u.Tier != nil && reservationsLimit < u.Tier.ReservationLimit {
  825. reservations, err := a.Reservations(username)
  826. if err != nil {
  827. return err
  828. } else if int64(len(reservations)) > reservationsLimit {
  829. return ErrTooManyReservations
  830. }
  831. }
  832. return nil
  833. }
  834. // CheckAllowAccess tests if a user may create an access control entry for the given topic.
  835. // If there are any ACL entries that are not owned by the user, an error is returned.
  836. // FIXME is this the same as HasReservation?
  837. func (a *Manager) CheckAllowAccess(username string, topic string) error {
  838. if (!AllowedUsername(username) && username != Everyone) || !AllowedTopic(topic) {
  839. return ErrInvalidArgument
  840. }
  841. rows, err := a.db.Query(selectOtherAccessCountQuery, topic, topic, username)
  842. if err != nil {
  843. return err
  844. }
  845. defer rows.Close()
  846. if !rows.Next() {
  847. return errNoRows
  848. }
  849. var otherCount int
  850. if err := rows.Scan(&otherCount); err != nil {
  851. return err
  852. }
  853. if otherCount > 0 {
  854. return errTopicOwnedByOthers
  855. }
  856. return nil
  857. }
  858. // AllowAccess adds or updates an entry in th access control list for a specific user. It controls
  859. // read/write access to a topic. The parameter topicPattern may include wildcards (*). The ACL entry
  860. // owner may either be a user (username), or the system (empty).
  861. func (a *Manager) AllowAccess(username string, topicPattern string, permission Permission) error {
  862. if !AllowedUsername(username) && username != Everyone {
  863. return ErrInvalidArgument
  864. } else if !AllowedTopicPattern(topicPattern) {
  865. return ErrInvalidArgument
  866. }
  867. owner := ""
  868. if _, err := a.db.Exec(upsertUserAccessQuery, username, toSQLWildcard(topicPattern), permission.IsRead(), permission.IsWrite(), owner, owner); err != nil {
  869. return err
  870. }
  871. return nil
  872. }
  873. // ResetAccess removes an access control list entry for a specific username/topic, or (if topic is
  874. // empty) for an entire user. The parameter topicPattern may include wildcards (*).
  875. func (a *Manager) ResetAccess(username string, topicPattern string) error {
  876. if !AllowedUsername(username) && username != Everyone && username != "" {
  877. return ErrInvalidArgument
  878. } else if !AllowedTopicPattern(topicPattern) && topicPattern != "" {
  879. return ErrInvalidArgument
  880. }
  881. if username == "" && topicPattern == "" {
  882. _, err := a.db.Exec(deleteAllAccessQuery, username)
  883. return err
  884. } else if topicPattern == "" {
  885. _, err := a.db.Exec(deleteUserAccessQuery, username, username)
  886. return err
  887. }
  888. _, err := a.db.Exec(deleteTopicAccessQuery, username, username, toSQLWildcard(topicPattern))
  889. return err
  890. }
  891. // AddReservation creates two access control entries for the given topic: one with full read/write access for the
  892. // given user, and one for Everyone with the permission passed as everyone. The user also owns the entries, and
  893. // can modify or delete them.
  894. func (a *Manager) AddReservation(username string, topic string, everyone Permission) error {
  895. if !AllowedUsername(username) || username == Everyone || !AllowedTopic(topic) {
  896. return ErrInvalidArgument
  897. }
  898. tx, err := a.db.Begin()
  899. if err != nil {
  900. return err
  901. }
  902. defer tx.Rollback()
  903. if _, err := tx.Exec(upsertUserAccessQuery, username, topic, true, true, username, username); err != nil {
  904. return err
  905. }
  906. if _, err := tx.Exec(upsertUserAccessQuery, Everyone, topic, everyone.IsRead(), everyone.IsWrite(), username, username); err != nil {
  907. return err
  908. }
  909. return tx.Commit()
  910. }
  911. // RemoveReservations deletes the access control entries associated with the given username/topic, as
  912. // well as all entries with Everyone/topic. This is the counterpart for AddReservation.
  913. func (a *Manager) RemoveReservations(username string, topics ...string) error {
  914. if !AllowedUsername(username) || username == Everyone || len(topics) == 0 {
  915. return ErrInvalidArgument
  916. }
  917. for _, topic := range topics {
  918. if !AllowedTopic(topic) {
  919. return ErrInvalidArgument
  920. }
  921. }
  922. tx, err := a.db.Begin()
  923. if err != nil {
  924. return err
  925. }
  926. defer tx.Rollback()
  927. for _, topic := range topics {
  928. if _, err := tx.Exec(deleteTopicAccessQuery, username, username, topic); err != nil {
  929. return err
  930. }
  931. if _, err := tx.Exec(deleteTopicAccessQuery, Everyone, Everyone, topic); err != nil {
  932. return err
  933. }
  934. }
  935. return tx.Commit()
  936. }
  937. // DefaultAccess returns the default read/write access if no access control entry matches
  938. func (a *Manager) DefaultAccess() Permission {
  939. return a.defaultAccess
  940. }
  941. // CreateTier creates a new tier in the database
  942. func (a *Manager) CreateTier(tier *Tier) error {
  943. if tier.ID == "" {
  944. tier.ID = util.RandomStringPrefix(tierIDPrefix, tierIDLength)
  945. }
  946. if _, err := a.db.Exec(insertTierQuery, tier.ID, tier.Code, tier.Name, tier.MessageLimit, int64(tier.MessageExpiryDuration.Seconds()), tier.EmailLimit, tier.ReservationLimit, tier.AttachmentFileSizeLimit, tier.AttachmentTotalSizeLimit, int64(tier.AttachmentExpiryDuration.Seconds()), tier.AttachmentBandwidthLimit, tier.StripePriceID); err != nil {
  947. return err
  948. }
  949. return nil
  950. }
  951. // ChangeBilling updates a user's billing fields, namely the Stripe customer ID, and subscription information
  952. func (a *Manager) ChangeBilling(username string, billing *Billing) error {
  953. if _, err := a.db.Exec(updateBillingQuery, nullString(billing.StripeCustomerID), nullString(billing.StripeSubscriptionID), nullString(string(billing.StripeSubscriptionStatus)), nullInt64(billing.StripeSubscriptionPaidUntil.Unix()), nullInt64(billing.StripeSubscriptionCancelAt.Unix()), username); err != nil {
  954. return err
  955. }
  956. return nil
  957. }
  958. // Tiers returns a list of all Tier structs
  959. func (a *Manager) Tiers() ([]*Tier, error) {
  960. rows, err := a.db.Query(selectTiersQuery)
  961. if err != nil {
  962. return nil, err
  963. }
  964. defer rows.Close()
  965. tiers := make([]*Tier, 0)
  966. for {
  967. tier, err := a.readTier(rows)
  968. if err == ErrTierNotFound {
  969. break
  970. } else if err != nil {
  971. return nil, err
  972. }
  973. tiers = append(tiers, tier)
  974. }
  975. return tiers, nil
  976. }
  977. // Tier returns a Tier based on the code, or ErrTierNotFound if it does not exist
  978. func (a *Manager) Tier(code string) (*Tier, error) {
  979. rows, err := a.db.Query(selectTierByCodeQuery, code)
  980. if err != nil {
  981. return nil, err
  982. }
  983. defer rows.Close()
  984. return a.readTier(rows)
  985. }
  986. // TierByStripePrice returns a Tier based on the Stripe price ID, or ErrTierNotFound if it does not exist
  987. func (a *Manager) TierByStripePrice(priceID string) (*Tier, error) {
  988. rows, err := a.db.Query(selectTierByPriceIDQuery, priceID)
  989. if err != nil {
  990. return nil, err
  991. }
  992. defer rows.Close()
  993. return a.readTier(rows)
  994. }
  995. func (a *Manager) readTier(rows *sql.Rows) (*Tier, error) {
  996. var id, code, name string
  997. var stripePriceID sql.NullString
  998. var messagesLimit, messagesExpiryDuration, emailsLimit, reservationsLimit, attachmentFileSizeLimit, attachmentTotalSizeLimit, attachmentExpiryDuration, attachmentBandwidthLimit sql.NullInt64
  999. if !rows.Next() {
  1000. return nil, ErrTierNotFound
  1001. }
  1002. if err := rows.Scan(&id, &code, &name, &messagesLimit, &messagesExpiryDuration, &emailsLimit, &reservationsLimit, &attachmentFileSizeLimit, &attachmentTotalSizeLimit, &attachmentExpiryDuration, &attachmentBandwidthLimit, &stripePriceID); err != nil {
  1003. return nil, err
  1004. } else if err := rows.Err(); err != nil {
  1005. return nil, err
  1006. }
  1007. // When changed, note readUser() as well
  1008. return &Tier{
  1009. ID: id,
  1010. Code: code,
  1011. Name: name,
  1012. MessageLimit: messagesLimit.Int64,
  1013. MessageExpiryDuration: time.Duration(messagesExpiryDuration.Int64) * time.Second,
  1014. EmailLimit: emailsLimit.Int64,
  1015. ReservationLimit: reservationsLimit.Int64,
  1016. AttachmentFileSizeLimit: attachmentFileSizeLimit.Int64,
  1017. AttachmentTotalSizeLimit: attachmentTotalSizeLimit.Int64,
  1018. AttachmentExpiryDuration: time.Duration(attachmentExpiryDuration.Int64) * time.Second,
  1019. AttachmentBandwidthLimit: attachmentBandwidthLimit.Int64,
  1020. StripePriceID: stripePriceID.String, // May be empty
  1021. }, nil
  1022. }
  1023. func toSQLWildcard(s string) string {
  1024. return strings.ReplaceAll(s, "*", "%")
  1025. }
  1026. func fromSQLWildcard(s string) string {
  1027. return strings.ReplaceAll(s, "%", "*")
  1028. }
  1029. func runStartupQueries(db *sql.DB, startupQueries string) error {
  1030. if _, err := db.Exec(startupQueries); err != nil {
  1031. return err
  1032. }
  1033. if _, err := db.Exec(builtinStartupQueries); err != nil {
  1034. return err
  1035. }
  1036. return nil
  1037. }
  1038. func setupDB(db *sql.DB) error {
  1039. // If 'schemaVersion' table does not exist, this must be a new database
  1040. rowsSV, err := db.Query(selectSchemaVersionQuery)
  1041. if err != nil {
  1042. return setupNewDB(db)
  1043. }
  1044. defer rowsSV.Close()
  1045. // If 'schemaVersion' table exists, read version and potentially upgrade
  1046. schemaVersion := 0
  1047. if !rowsSV.Next() {
  1048. return errors.New("cannot determine schema version: database file may be corrupt")
  1049. }
  1050. if err := rowsSV.Scan(&schemaVersion); err != nil {
  1051. return err
  1052. }
  1053. rowsSV.Close()
  1054. // Do migrations
  1055. if schemaVersion == currentSchemaVersion {
  1056. return nil
  1057. } else if schemaVersion == 1 {
  1058. return migrateFrom1(db)
  1059. }
  1060. return fmt.Errorf("unexpected schema version found: %d", schemaVersion)
  1061. }
  1062. func setupNewDB(db *sql.DB) error {
  1063. if _, err := db.Exec(createTablesQueries); err != nil {
  1064. return err
  1065. }
  1066. if _, err := db.Exec(insertSchemaVersion, currentSchemaVersion); err != nil {
  1067. return err
  1068. }
  1069. return nil
  1070. }
  1071. func migrateFrom1(db *sql.DB) error {
  1072. log.Info("Migrating user database schema: from 1 to 2")
  1073. tx, err := db.Begin()
  1074. if err != nil {
  1075. return err
  1076. }
  1077. defer tx.Rollback()
  1078. // Rename user -> user_old, and create new tables
  1079. if _, err := tx.Exec(migrate1To2RenameUserTableQueryNoTx); err != nil {
  1080. return err
  1081. }
  1082. if _, err := tx.Exec(createTablesQueriesNoTx); err != nil {
  1083. return err
  1084. }
  1085. // Insert users from user_old into new user table, with ID and sync_topic
  1086. rows, err := tx.Query(migrate1To2SelectAllOldUsernamesNoTx)
  1087. if err != nil {
  1088. return err
  1089. }
  1090. defer rows.Close()
  1091. usernames := make([]string, 0)
  1092. for rows.Next() {
  1093. var username string
  1094. if err := rows.Scan(&username); err != nil {
  1095. return err
  1096. }
  1097. usernames = append(usernames, username)
  1098. }
  1099. if err := rows.Close(); err != nil {
  1100. return err
  1101. }
  1102. for _, username := range usernames {
  1103. userID := util.RandomStringPrefix(userIDPrefix, userIDLength)
  1104. syncTopic := util.RandomStringPrefix(syncTopicPrefix, syncTopicLength)
  1105. if _, err := tx.Exec(migrate1To2InsertUserNoTx, userID, syncTopic, username); err != nil {
  1106. return err
  1107. }
  1108. }
  1109. // Migrate old "access" table to "user_access" and drop "access" and "user_old"
  1110. if _, err := tx.Exec(migrate1To2InsertFromOldTablesAndDropNoTx); err != nil {
  1111. return err
  1112. }
  1113. if _, err := tx.Exec(updateSchemaVersion, 2); err != nil {
  1114. return err
  1115. }
  1116. if err := tx.Commit(); err != nil {
  1117. return err
  1118. }
  1119. return nil // Update this when a new version is added
  1120. }
  1121. func nullString(s string) sql.NullString {
  1122. if s == "" {
  1123. return sql.NullString{}
  1124. }
  1125. return sql.NullString{String: s, Valid: true}
  1126. }
  1127. func nullInt64(v int64) sql.NullInt64 {
  1128. if v == 0 {
  1129. return sql.NullInt64{}
  1130. }
  1131. return sql.NullInt64{Int64: v, Valid: true}
  1132. }