manager.go 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678
  1. // Package user deals with authentication and authorization against topics
  2. package user
  3. import (
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "github.com/mattn/go-sqlite3"
  9. "github.com/stripe/stripe-go/v74"
  10. "golang.org/x/crypto/bcrypt"
  11. "heckel.io/ntfy/v2/log"
  12. "heckel.io/ntfy/v2/util"
  13. "net/netip"
  14. "strings"
  15. "sync"
  16. "time"
  17. )
  18. const (
  19. tierIDPrefix = "ti_"
  20. tierIDLength = 8
  21. syncTopicPrefix = "st_"
  22. syncTopicLength = 16
  23. userIDPrefix = "u_"
  24. userIDLength = 12
  25. userAuthIntentionalSlowDownHash = "$2a$10$YFCQvqQDwIIwnJM1xkAYOeih0dg17UVGanaTStnrSzC8NCWxcLDwy" // Cost should match DefaultUserPasswordBcryptCost
  26. userHardDeleteAfterDuration = 7 * 24 * time.Hour
  27. tokenPrefix = "tk_"
  28. tokenLength = 32
  29. tokenMaxCount = 20 // Only keep this many tokens in the table per user
  30. tag = "user_manager"
  31. )
  32. // Default constants that may be overridden by configs
  33. const (
  34. DefaultUserStatsQueueWriterInterval = 33 * time.Second
  35. DefaultUserPasswordBcryptCost = 10
  36. )
  37. var (
  38. errNoTokenProvided = errors.New("no token provided")
  39. errTopicOwnedByOthers = errors.New("topic owned by others")
  40. errNoRows = errors.New("no rows found")
  41. )
  42. // Manager-related queries
  43. const (
  44. createTablesQueries = `
  45. BEGIN;
  46. CREATE TABLE IF NOT EXISTS tier (
  47. id TEXT PRIMARY KEY,
  48. code TEXT NOT NULL,
  49. name TEXT NOT NULL,
  50. messages_limit INT NOT NULL,
  51. messages_expiry_duration INT NOT NULL,
  52. emails_limit INT NOT NULL,
  53. calls_limit INT NOT NULL,
  54. reservations_limit INT NOT NULL,
  55. attachment_file_size_limit INT NOT NULL,
  56. attachment_total_size_limit INT NOT NULL,
  57. attachment_expiry_duration INT NOT NULL,
  58. attachment_bandwidth_limit INT NOT NULL,
  59. stripe_monthly_price_id TEXT,
  60. stripe_yearly_price_id TEXT
  61. );
  62. CREATE UNIQUE INDEX idx_tier_code ON tier (code);
  63. CREATE UNIQUE INDEX idx_tier_stripe_monthly_price_id ON tier (stripe_monthly_price_id);
  64. CREATE UNIQUE INDEX idx_tier_stripe_yearly_price_id ON tier (stripe_yearly_price_id);
  65. CREATE TABLE IF NOT EXISTS user (
  66. id TEXT PRIMARY KEY,
  67. tier_id TEXT,
  68. user TEXT NOT NULL,
  69. pass TEXT NOT NULL,
  70. role TEXT CHECK (role IN ('anonymous', 'admin', 'user')) NOT NULL,
  71. prefs JSON NOT NULL DEFAULT '{}',
  72. sync_topic TEXT NOT NULL,
  73. stats_messages INT NOT NULL DEFAULT (0),
  74. stats_emails INT NOT NULL DEFAULT (0),
  75. stats_calls INT NOT NULL DEFAULT (0),
  76. stripe_customer_id TEXT,
  77. stripe_subscription_id TEXT,
  78. stripe_subscription_status TEXT,
  79. stripe_subscription_interval TEXT,
  80. stripe_subscription_paid_until INT,
  81. stripe_subscription_cancel_at INT,
  82. created INT NOT NULL,
  83. deleted INT,
  84. FOREIGN KEY (tier_id) REFERENCES tier (id)
  85. );
  86. CREATE UNIQUE INDEX idx_user ON user (user);
  87. CREATE UNIQUE INDEX idx_user_stripe_customer_id ON user (stripe_customer_id);
  88. CREATE UNIQUE INDEX idx_user_stripe_subscription_id ON user (stripe_subscription_id);
  89. CREATE TABLE IF NOT EXISTS user_access (
  90. user_id TEXT NOT NULL,
  91. topic TEXT NOT NULL,
  92. read INT NOT NULL,
  93. write INT NOT NULL,
  94. owner_user_id INT,
  95. PRIMARY KEY (user_id, topic),
  96. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE,
  97. FOREIGN KEY (owner_user_id) REFERENCES user (id) ON DELETE CASCADE
  98. );
  99. CREATE TABLE IF NOT EXISTS user_token (
  100. user_id TEXT NOT NULL,
  101. token TEXT NOT NULL,
  102. label TEXT NOT NULL,
  103. last_access INT NOT NULL,
  104. last_origin TEXT NOT NULL,
  105. expires INT NOT NULL,
  106. PRIMARY KEY (user_id, token),
  107. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE
  108. );
  109. CREATE TABLE IF NOT EXISTS user_phone (
  110. user_id TEXT NOT NULL,
  111. phone_number TEXT NOT NULL,
  112. PRIMARY KEY (user_id, phone_number),
  113. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE
  114. );
  115. CREATE TABLE IF NOT EXISTS schemaVersion (
  116. id INT PRIMARY KEY,
  117. version INT NOT NULL
  118. );
  119. INSERT INTO user (id, user, pass, role, sync_topic, created)
  120. VALUES ('` + everyoneID + `', '*', '', 'anonymous', '', UNIXEPOCH())
  121. ON CONFLICT (id) DO NOTHING;
  122. COMMIT;
  123. `
  124. builtinStartupQueries = `
  125. PRAGMA foreign_keys = ON;
  126. `
  127. selectUserByIDQuery = `
  128. SELECT u.id, u.user, u.pass, u.role, u.prefs, u.sync_topic, u.stats_messages, u.stats_emails, u.stats_calls, u.stripe_customer_id, u.stripe_subscription_id, u.stripe_subscription_status, u.stripe_subscription_interval, 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.calls_limit, t.reservations_limit, t.attachment_file_size_limit, t.attachment_total_size_limit, t.attachment_expiry_duration, t.attachment_bandwidth_limit, t.stripe_monthly_price_id, t.stripe_yearly_price_id
  129. FROM user u
  130. LEFT JOIN tier t on t.id = u.tier_id
  131. WHERE u.id = ?
  132. `
  133. selectUserByNameQuery = `
  134. SELECT u.id, u.user, u.pass, u.role, u.prefs, u.sync_topic, u.stats_messages, u.stats_emails, u.stats_calls, u.stripe_customer_id, u.stripe_subscription_id, u.stripe_subscription_status, u.stripe_subscription_interval, 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.calls_limit, t.reservations_limit, t.attachment_file_size_limit, t.attachment_total_size_limit, t.attachment_expiry_duration, t.attachment_bandwidth_limit, t.stripe_monthly_price_id, t.stripe_yearly_price_id
  135. FROM user u
  136. LEFT JOIN tier t on t.id = u.tier_id
  137. WHERE user = ?
  138. `
  139. selectUserByTokenQuery = `
  140. SELECT u.id, u.user, u.pass, u.role, u.prefs, u.sync_topic, u.stats_messages, u.stats_emails, u.stats_calls, u.stripe_customer_id, u.stripe_subscription_id, u.stripe_subscription_status, u.stripe_subscription_interval, 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.calls_limit, t.reservations_limit, t.attachment_file_size_limit, t.attachment_total_size_limit, t.attachment_expiry_duration, t.attachment_bandwidth_limit, t.stripe_monthly_price_id, t.stripe_yearly_price_id
  141. FROM user u
  142. JOIN user_token tk on u.id = tk.user_id
  143. LEFT JOIN tier t on t.id = u.tier_id
  144. WHERE tk.token = ? AND (tk.expires = 0 OR tk.expires >= ?)
  145. `
  146. selectUserByStripeCustomerIDQuery = `
  147. SELECT u.id, u.user, u.pass, u.role, u.prefs, u.sync_topic, u.stats_messages, u.stats_emails, u.stats_calls, u.stripe_customer_id, u.stripe_subscription_id, u.stripe_subscription_status, u.stripe_subscription_interval, 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.calls_limit, t.reservations_limit, t.attachment_file_size_limit, t.attachment_total_size_limit, t.attachment_expiry_duration, t.attachment_bandwidth_limit, t.stripe_monthly_price_id, t.stripe_yearly_price_id
  148. FROM user u
  149. LEFT JOIN tier t on t.id = u.tier_id
  150. WHERE u.stripe_customer_id = ?
  151. `
  152. selectTopicPermsQuery = `
  153. SELECT read, write
  154. FROM user_access a
  155. JOIN user u ON u.id = a.user_id
  156. WHERE (u.user = ? OR u.user = ?) AND ? LIKE a.topic ESCAPE '\'
  157. ORDER BY u.user DESC, LENGTH(a.topic) DESC, a.write DESC
  158. `
  159. insertUserQuery = `
  160. INSERT INTO user (id, user, pass, role, sync_topic, created)
  161. VALUES (?, ?, ?, ?, ?, ?)
  162. `
  163. selectUsernamesQuery = `
  164. SELECT user
  165. FROM user
  166. ORDER BY
  167. CASE role
  168. WHEN 'admin' THEN 1
  169. WHEN 'anonymous' THEN 3
  170. ELSE 2
  171. END, user
  172. `
  173. selectUserCountQuery = `SELECT COUNT(*) FROM user`
  174. updateUserPassQuery = `UPDATE user SET pass = ? WHERE user = ?`
  175. updateUserRoleQuery = `UPDATE user SET role = ? WHERE user = ?`
  176. updateUserPrefsQuery = `UPDATE user SET prefs = ? WHERE id = ?`
  177. updateUserStatsQuery = `UPDATE user SET stats_messages = ?, stats_emails = ?, stats_calls = ? WHERE id = ?`
  178. updateUserStatsResetAllQuery = `UPDATE user SET stats_messages = 0, stats_emails = 0, stats_calls = 0`
  179. updateUserDeletedQuery = `UPDATE user SET deleted = ? WHERE id = ?`
  180. deleteUsersMarkedQuery = `DELETE FROM user WHERE deleted < ?`
  181. deleteUserQuery = `DELETE FROM user WHERE user = ?`
  182. upsertUserAccessQuery = `
  183. INSERT INTO user_access (user_id, topic, read, write, owner_user_id)
  184. VALUES ((SELECT id FROM user WHERE user = ?), ?, ?, ?, (SELECT IIF(?='',NULL,(SELECT id FROM user WHERE user=?))))
  185. ON CONFLICT (user_id, topic)
  186. DO UPDATE SET read=excluded.read, write=excluded.write, owner_user_id=excluded.owner_user_id
  187. `
  188. selectUserAllAccessQuery = `
  189. SELECT user_id, topic, read, write
  190. FROM user_access
  191. ORDER BY LENGTH(topic) DESC, write DESC, read DESC, topic
  192. `
  193. selectUserAccessQuery = `
  194. SELECT topic, read, write
  195. FROM user_access
  196. WHERE user_id = (SELECT id FROM user WHERE user = ?)
  197. ORDER BY LENGTH(topic) DESC, write DESC, read DESC, topic
  198. `
  199. selectUserReservationsQuery = `
  200. SELECT a_user.topic, a_user.read, a_user.write, a_everyone.read AS everyone_read, a_everyone.write AS everyone_write
  201. FROM user_access a_user
  202. LEFT JOIN user_access a_everyone ON a_user.topic = a_everyone.topic AND a_everyone.user_id = (SELECT id FROM user WHERE user = ?)
  203. WHERE a_user.user_id = a_user.owner_user_id
  204. AND a_user.owner_user_id = (SELECT id FROM user WHERE user = ?)
  205. ORDER BY a_user.topic
  206. `
  207. selectUserReservationsCountQuery = `
  208. SELECT COUNT(*)
  209. FROM user_access
  210. WHERE user_id = owner_user_id
  211. AND owner_user_id = (SELECT id FROM user WHERE user = ?)
  212. `
  213. selectUserReservationsOwnerQuery = `
  214. SELECT owner_user_id
  215. FROM user_access
  216. WHERE topic = ?
  217. AND user_id = owner_user_id
  218. `
  219. selectUserHasReservationQuery = `
  220. SELECT COUNT(*)
  221. FROM user_access
  222. WHERE user_id = owner_user_id
  223. AND owner_user_id = (SELECT id FROM user WHERE user = ?)
  224. AND topic = ?
  225. `
  226. selectOtherAccessCountQuery = `
  227. SELECT COUNT(*)
  228. FROM user_access
  229. WHERE (topic = ? OR ? LIKE topic ESCAPE '\')
  230. AND (owner_user_id IS NULL OR owner_user_id != (SELECT id FROM user WHERE user = ?))
  231. `
  232. deleteAllAccessQuery = `DELETE FROM user_access`
  233. deleteUserAccessQuery = `
  234. DELETE FROM user_access
  235. WHERE user_id = (SELECT id FROM user WHERE user = ?)
  236. OR owner_user_id = (SELECT id FROM user WHERE user = ?)
  237. `
  238. deleteTopicAccessQuery = `
  239. DELETE FROM user_access
  240. WHERE (user_id = (SELECT id FROM user WHERE user = ?) OR owner_user_id = (SELECT id FROM user WHERE user = ?))
  241. AND topic = ?
  242. `
  243. selectTokenCountQuery = `SELECT COUNT(*) FROM user_token WHERE user_id = ?`
  244. selectTokensQuery = `SELECT token, label, last_access, last_origin, expires FROM user_token WHERE user_id = ?`
  245. selectTokenQuery = `SELECT token, label, last_access, last_origin, expires FROM user_token WHERE user_id = ? AND token = ?`
  246. insertTokenQuery = `INSERT INTO user_token (user_id, token, label, last_access, last_origin, expires) VALUES (?, ?, ?, ?, ?, ?)`
  247. updateTokenExpiryQuery = `UPDATE user_token SET expires = ? WHERE user_id = ? AND token = ?`
  248. updateTokenLabelQuery = `UPDATE user_token SET label = ? WHERE user_id = ? AND token = ?`
  249. updateTokenLastAccessQuery = `UPDATE user_token SET last_access = ?, last_origin = ? WHERE token = ?`
  250. deleteTokenQuery = `DELETE FROM user_token WHERE user_id = ? AND token = ?`
  251. deleteAllTokenQuery = `DELETE FROM user_token WHERE user_id = ?`
  252. deleteExpiredTokensQuery = `DELETE FROM user_token WHERE expires > 0 AND expires < ?`
  253. deleteExcessTokensQuery = `
  254. DELETE FROM user_token
  255. WHERE user_id = ?
  256. AND (user_id, token) NOT IN (
  257. SELECT user_id, token
  258. FROM user_token
  259. WHERE user_id = ?
  260. ORDER BY expires DESC
  261. LIMIT ?
  262. )
  263. `
  264. selectPhoneNumbersQuery = `SELECT phone_number FROM user_phone WHERE user_id = ?`
  265. insertPhoneNumberQuery = `INSERT INTO user_phone (user_id, phone_number) VALUES (?, ?)`
  266. deletePhoneNumberQuery = `DELETE FROM user_phone WHERE user_id = ? AND phone_number = ?`
  267. insertTierQuery = `
  268. INSERT INTO tier (id, code, name, messages_limit, messages_expiry_duration, emails_limit, calls_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_monthly_price_id, stripe_yearly_price_id)
  269. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  270. `
  271. updateTierQuery = `
  272. UPDATE tier
  273. SET name = ?, messages_limit = ?, messages_expiry_duration = ?, emails_limit = ?, calls_limit = ?, reservations_limit = ?, attachment_file_size_limit = ?, attachment_total_size_limit = ?, attachment_expiry_duration = ?, attachment_bandwidth_limit = ?, stripe_monthly_price_id = ?, stripe_yearly_price_id = ?
  274. WHERE code = ?
  275. `
  276. selectTiersQuery = `
  277. SELECT id, code, name, messages_limit, messages_expiry_duration, emails_limit, calls_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_monthly_price_id, stripe_yearly_price_id
  278. FROM tier
  279. `
  280. selectTierByCodeQuery = `
  281. SELECT id, code, name, messages_limit, messages_expiry_duration, emails_limit, calls_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_monthly_price_id, stripe_yearly_price_id
  282. FROM tier
  283. WHERE code = ?
  284. `
  285. selectTierByPriceIDQuery = `
  286. SELECT id, code, name, messages_limit, messages_expiry_duration, emails_limit, calls_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_monthly_price_id, stripe_yearly_price_id
  287. FROM tier
  288. WHERE (stripe_monthly_price_id = ? OR stripe_yearly_price_id = ?)
  289. `
  290. updateUserTierQuery = `UPDATE user SET tier_id = (SELECT id FROM tier WHERE code = ?) WHERE user = ?`
  291. deleteUserTierQuery = `UPDATE user SET tier_id = null WHERE user = ?`
  292. deleteTierQuery = `DELETE FROM tier WHERE code = ?`
  293. updateBillingQuery = `
  294. UPDATE user
  295. SET stripe_customer_id = ?, stripe_subscription_id = ?, stripe_subscription_status = ?, stripe_subscription_interval = ?, stripe_subscription_paid_until = ?, stripe_subscription_cancel_at = ?
  296. WHERE user = ?
  297. `
  298. )
  299. // Schema management queries
  300. const (
  301. currentSchemaVersion = 5
  302. insertSchemaVersion = `INSERT INTO schemaVersion VALUES (1, ?)`
  303. updateSchemaVersion = `UPDATE schemaVersion SET version = ? WHERE id = 1`
  304. selectSchemaVersionQuery = `SELECT version FROM schemaVersion WHERE id = 1`
  305. // 1 -> 2 (complex migration!)
  306. migrate1To2CreateTablesQueries = `
  307. ALTER TABLE user RENAME TO user_old;
  308. CREATE TABLE IF NOT EXISTS tier (
  309. id TEXT PRIMARY KEY,
  310. code TEXT NOT NULL,
  311. name TEXT NOT NULL,
  312. messages_limit INT NOT NULL,
  313. messages_expiry_duration INT NOT NULL,
  314. emails_limit INT NOT NULL,
  315. reservations_limit INT NOT NULL,
  316. attachment_file_size_limit INT NOT NULL,
  317. attachment_total_size_limit INT NOT NULL,
  318. attachment_expiry_duration INT NOT NULL,
  319. attachment_bandwidth_limit INT NOT NULL,
  320. stripe_price_id TEXT
  321. );
  322. CREATE UNIQUE INDEX idx_tier_code ON tier (code);
  323. CREATE UNIQUE INDEX idx_tier_price_id ON tier (stripe_price_id);
  324. CREATE TABLE IF NOT EXISTS user (
  325. id TEXT PRIMARY KEY,
  326. tier_id TEXT,
  327. user TEXT NOT NULL,
  328. pass TEXT NOT NULL,
  329. role TEXT CHECK (role IN ('anonymous', 'admin', 'user')) NOT NULL,
  330. prefs JSON NOT NULL DEFAULT '{}',
  331. sync_topic TEXT NOT NULL,
  332. stats_messages INT NOT NULL DEFAULT (0),
  333. stats_emails INT NOT NULL DEFAULT (0),
  334. stripe_customer_id TEXT,
  335. stripe_subscription_id TEXT,
  336. stripe_subscription_status TEXT,
  337. stripe_subscription_paid_until INT,
  338. stripe_subscription_cancel_at INT,
  339. created INT NOT NULL,
  340. deleted INT,
  341. FOREIGN KEY (tier_id) REFERENCES tier (id)
  342. );
  343. CREATE UNIQUE INDEX idx_user ON user (user);
  344. CREATE UNIQUE INDEX idx_user_stripe_customer_id ON user (stripe_customer_id);
  345. CREATE UNIQUE INDEX idx_user_stripe_subscription_id ON user (stripe_subscription_id);
  346. CREATE TABLE IF NOT EXISTS user_access (
  347. user_id TEXT NOT NULL,
  348. topic TEXT NOT NULL,
  349. read INT NOT NULL,
  350. write INT NOT NULL,
  351. owner_user_id INT,
  352. PRIMARY KEY (user_id, topic),
  353. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE,
  354. FOREIGN KEY (owner_user_id) REFERENCES user (id) ON DELETE CASCADE
  355. );
  356. CREATE TABLE IF NOT EXISTS user_token (
  357. user_id TEXT NOT NULL,
  358. token TEXT NOT NULL,
  359. label TEXT NOT NULL,
  360. last_access INT NOT NULL,
  361. last_origin TEXT NOT NULL,
  362. expires INT NOT NULL,
  363. PRIMARY KEY (user_id, token),
  364. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE
  365. );
  366. CREATE TABLE IF NOT EXISTS schemaVersion (
  367. id INT PRIMARY KEY,
  368. version INT NOT NULL
  369. );
  370. INSERT INTO user (id, user, pass, role, sync_topic, created)
  371. VALUES ('u_everyone', '*', '', 'anonymous', '', UNIXEPOCH())
  372. ON CONFLICT (id) DO NOTHING;
  373. `
  374. migrate1To2SelectAllOldUsernamesNoTx = `SELECT user FROM user_old`
  375. migrate1To2InsertUserNoTx = `
  376. INSERT INTO user (id, user, pass, role, sync_topic, created)
  377. SELECT ?, user, pass, role, ?, UNIXEPOCH() FROM user_old WHERE user = ?
  378. `
  379. migrate1To2InsertFromOldTablesAndDropNoTx = `
  380. INSERT INTO user_access (user_id, topic, read, write)
  381. SELECT u.id, a.topic, a.read, a.write
  382. FROM user u
  383. JOIN access a ON u.user = a.user;
  384. DROP TABLE access;
  385. DROP TABLE user_old;
  386. `
  387. // 2 -> 3
  388. migrate2To3UpdateQueries = `
  389. ALTER TABLE user ADD COLUMN stripe_subscription_interval TEXT;
  390. ALTER TABLE tier RENAME COLUMN stripe_price_id TO stripe_monthly_price_id;
  391. ALTER TABLE tier ADD COLUMN stripe_yearly_price_id TEXT;
  392. DROP INDEX IF EXISTS idx_tier_price_id;
  393. CREATE UNIQUE INDEX idx_tier_stripe_monthly_price_id ON tier (stripe_monthly_price_id);
  394. CREATE UNIQUE INDEX idx_tier_stripe_yearly_price_id ON tier (stripe_yearly_price_id);
  395. `
  396. // 3 -> 4
  397. migrate3To4UpdateQueries = `
  398. ALTER TABLE tier ADD COLUMN calls_limit INT NOT NULL DEFAULT (0);
  399. ALTER TABLE user ADD COLUMN stats_calls INT NOT NULL DEFAULT (0);
  400. CREATE TABLE IF NOT EXISTS user_phone (
  401. user_id TEXT NOT NULL,
  402. phone_number TEXT NOT NULL,
  403. PRIMARY KEY (user_id, phone_number),
  404. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE
  405. );
  406. `
  407. // 4 -> 5
  408. migrate4To5UpdateQueries = `
  409. UPDATE user_access SET topic = REPLACE(topic, '_', '\_');
  410. `
  411. )
  412. var (
  413. migrations = map[int]func(db *sql.DB) error{
  414. 1: migrateFrom1,
  415. 2: migrateFrom2,
  416. 3: migrateFrom3,
  417. 4: migrateFrom4,
  418. }
  419. )
  420. // Manager is an implementation of Manager. It stores users and access control list
  421. // in a SQLite database.
  422. type Manager struct {
  423. db *sql.DB
  424. defaultAccess Permission // Default permission if no ACL matches
  425. statsQueue map[string]*Stats // "Queue" to asynchronously write user stats to the database (UserID -> Stats)
  426. tokenQueue map[string]*TokenUpdate // "Queue" to asynchronously write token access stats to the database (Token ID -> TokenUpdate)
  427. bcryptCost int // Makes testing easier
  428. mu sync.Mutex
  429. }
  430. var _ Auther = (*Manager)(nil)
  431. // NewManager creates a new Manager instance
  432. func NewManager(filename, startupQueries string, defaultAccess Permission, bcryptCost int, queueWriterInterval time.Duration) (*Manager, error) {
  433. db, err := sql.Open("sqlite3", filename)
  434. if err != nil {
  435. return nil, err
  436. }
  437. if err := setupDB(db); err != nil {
  438. return nil, err
  439. }
  440. if err := runStartupQueries(db, startupQueries); err != nil {
  441. return nil, err
  442. }
  443. manager := &Manager{
  444. db: db,
  445. defaultAccess: defaultAccess,
  446. statsQueue: make(map[string]*Stats),
  447. tokenQueue: make(map[string]*TokenUpdate),
  448. bcryptCost: bcryptCost,
  449. }
  450. go manager.asyncQueueWriter(queueWriterInterval)
  451. return manager, nil
  452. }
  453. // Authenticate checks username and password and returns a User if correct, and the user has not been
  454. // marked as deleted. The method returns in constant-ish time, regardless of whether the user exists or
  455. // the password is correct or incorrect.
  456. func (a *Manager) Authenticate(username, password string) (*User, error) {
  457. if username == Everyone {
  458. return nil, ErrUnauthenticated
  459. }
  460. user, err := a.User(username)
  461. if err != nil {
  462. log.Tag(tag).Field("user_name", username).Err(err).Trace("Authentication of user failed (1)")
  463. bcrypt.CompareHashAndPassword([]byte(userAuthIntentionalSlowDownHash), []byte("intentional slow-down to avoid timing attacks"))
  464. return nil, ErrUnauthenticated
  465. } else if user.Deleted {
  466. log.Tag(tag).Field("user_name", username).Trace("Authentication of user failed (2): user marked deleted")
  467. bcrypt.CompareHashAndPassword([]byte(userAuthIntentionalSlowDownHash), []byte("intentional slow-down to avoid timing attacks"))
  468. return nil, ErrUnauthenticated
  469. } else if err := bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(password)); err != nil {
  470. log.Tag(tag).Field("user_name", username).Err(err).Trace("Authentication of user failed (3)")
  471. return nil, ErrUnauthenticated
  472. }
  473. return user, nil
  474. }
  475. // AuthenticateToken checks if the token exists and returns the associated User if it does.
  476. // The method sets the User.Token value to the token that was used for authentication.
  477. func (a *Manager) AuthenticateToken(token string) (*User, error) {
  478. if len(token) != tokenLength {
  479. return nil, ErrUnauthenticated
  480. }
  481. user, err := a.userByToken(token)
  482. if err != nil {
  483. log.Tag(tag).Field("token", token).Err(err).Trace("Authentication of token failed")
  484. return nil, ErrUnauthenticated
  485. }
  486. user.Token = token
  487. return user, nil
  488. }
  489. // CreateToken generates a random token for the given user and returns it. The token expires
  490. // after a fixed duration unless ChangeToken is called. This function also prunes tokens for the
  491. // given user, if there are too many of them.
  492. func (a *Manager) CreateToken(userID, label string, expires time.Time, origin netip.Addr) (*Token, error) {
  493. token := util.RandomLowerStringPrefix(tokenPrefix, tokenLength) // Lowercase only to support "<topic>+<token>@<domain>" email addresses
  494. tx, err := a.db.Begin()
  495. if err != nil {
  496. return nil, err
  497. }
  498. defer tx.Rollback()
  499. access := time.Now()
  500. if _, err := tx.Exec(insertTokenQuery, userID, token, label, access.Unix(), origin.String(), expires.Unix()); err != nil {
  501. return nil, err
  502. }
  503. rows, err := tx.Query(selectTokenCountQuery, userID)
  504. if err != nil {
  505. return nil, err
  506. }
  507. defer rows.Close()
  508. if !rows.Next() {
  509. return nil, errNoRows
  510. }
  511. var tokenCount int
  512. if err := rows.Scan(&tokenCount); err != nil {
  513. return nil, err
  514. }
  515. if tokenCount >= tokenMaxCount {
  516. // This pruning logic is done in two queries for efficiency. The SELECT above is a lookup
  517. // on two indices, whereas the query below is a full table scan.
  518. if _, err := tx.Exec(deleteExcessTokensQuery, userID, userID, tokenMaxCount); err != nil {
  519. return nil, err
  520. }
  521. }
  522. if err := tx.Commit(); err != nil {
  523. return nil, err
  524. }
  525. return &Token{
  526. Value: token,
  527. Label: label,
  528. LastAccess: access,
  529. LastOrigin: origin,
  530. Expires: expires,
  531. }, nil
  532. }
  533. // Tokens returns all existing tokens for the user with the given user ID
  534. func (a *Manager) Tokens(userID string) ([]*Token, error) {
  535. rows, err := a.db.Query(selectTokensQuery, userID)
  536. if err != nil {
  537. return nil, err
  538. }
  539. defer rows.Close()
  540. tokens := make([]*Token, 0)
  541. for {
  542. token, err := a.readToken(rows)
  543. if err == ErrTokenNotFound {
  544. break
  545. } else if err != nil {
  546. return nil, err
  547. }
  548. tokens = append(tokens, token)
  549. }
  550. return tokens, nil
  551. }
  552. // Token returns a specific token for a user
  553. func (a *Manager) Token(userID, token string) (*Token, error) {
  554. rows, err := a.db.Query(selectTokenQuery, userID, token)
  555. if err != nil {
  556. return nil, err
  557. }
  558. defer rows.Close()
  559. return a.readToken(rows)
  560. }
  561. func (a *Manager) readToken(rows *sql.Rows) (*Token, error) {
  562. var token, label, lastOrigin string
  563. var lastAccess, expires int64
  564. if !rows.Next() {
  565. return nil, ErrTokenNotFound
  566. }
  567. if err := rows.Scan(&token, &label, &lastAccess, &lastOrigin, &expires); err != nil {
  568. return nil, err
  569. } else if err := rows.Err(); err != nil {
  570. return nil, err
  571. }
  572. lastOriginIP, err := netip.ParseAddr(lastOrigin)
  573. if err != nil {
  574. lastOriginIP = netip.IPv4Unspecified()
  575. }
  576. return &Token{
  577. Value: token,
  578. Label: label,
  579. LastAccess: time.Unix(lastAccess, 0),
  580. LastOrigin: lastOriginIP,
  581. Expires: time.Unix(expires, 0),
  582. }, nil
  583. }
  584. // ChangeToken updates a token's label and/or expiry date
  585. func (a *Manager) ChangeToken(userID, token string, label *string, expires *time.Time) (*Token, error) {
  586. if token == "" {
  587. return nil, errNoTokenProvided
  588. }
  589. tx, err := a.db.Begin()
  590. if err != nil {
  591. return nil, err
  592. }
  593. defer tx.Rollback()
  594. if label != nil {
  595. if _, err := tx.Exec(updateTokenLabelQuery, *label, userID, token); err != nil {
  596. return nil, err
  597. }
  598. }
  599. if expires != nil {
  600. if _, err := tx.Exec(updateTokenExpiryQuery, expires.Unix(), userID, token); err != nil {
  601. return nil, err
  602. }
  603. }
  604. if err := tx.Commit(); err != nil {
  605. return nil, err
  606. }
  607. return a.Token(userID, token)
  608. }
  609. // RemoveToken deletes the token defined in User.Token
  610. func (a *Manager) RemoveToken(userID, token string) error {
  611. if token == "" {
  612. return errNoTokenProvided
  613. }
  614. if _, err := a.db.Exec(deleteTokenQuery, userID, token); err != nil {
  615. return err
  616. }
  617. return nil
  618. }
  619. // RemoveExpiredTokens deletes all expired tokens from the database
  620. func (a *Manager) RemoveExpiredTokens() error {
  621. if _, err := a.db.Exec(deleteExpiredTokensQuery, time.Now().Unix()); err != nil {
  622. return err
  623. }
  624. return nil
  625. }
  626. // PhoneNumbers returns all phone numbers for the user with the given user ID
  627. func (a *Manager) PhoneNumbers(userID string) ([]string, error) {
  628. rows, err := a.db.Query(selectPhoneNumbersQuery, userID)
  629. if err != nil {
  630. return nil, err
  631. }
  632. defer rows.Close()
  633. phoneNumbers := make([]string, 0)
  634. for {
  635. phoneNumber, err := a.readPhoneNumber(rows)
  636. if err == ErrPhoneNumberNotFound {
  637. break
  638. } else if err != nil {
  639. return nil, err
  640. }
  641. phoneNumbers = append(phoneNumbers, phoneNumber)
  642. }
  643. return phoneNumbers, nil
  644. }
  645. func (a *Manager) readPhoneNumber(rows *sql.Rows) (string, error) {
  646. var phoneNumber string
  647. if !rows.Next() {
  648. return "", ErrPhoneNumberNotFound
  649. }
  650. if err := rows.Scan(&phoneNumber); err != nil {
  651. return "", err
  652. } else if err := rows.Err(); err != nil {
  653. return "", err
  654. }
  655. return phoneNumber, nil
  656. }
  657. // AddPhoneNumber adds a phone number to the user with the given user ID
  658. func (a *Manager) AddPhoneNumber(userID string, phoneNumber string) error {
  659. if _, err := a.db.Exec(insertPhoneNumberQuery, userID, phoneNumber); err != nil {
  660. if sqliteErr, ok := err.(sqlite3.Error); ok && sqliteErr.ExtendedCode == sqlite3.ErrConstraintUnique {
  661. return ErrPhoneNumberExists
  662. }
  663. return err
  664. }
  665. return nil
  666. }
  667. // RemovePhoneNumber deletes a phone number from the user with the given user ID
  668. func (a *Manager) RemovePhoneNumber(userID string, phoneNumber string) error {
  669. _, err := a.db.Exec(deletePhoneNumberQuery, userID, phoneNumber)
  670. return err
  671. }
  672. // RemoveDeletedUsers deletes all users that have been marked deleted for
  673. func (a *Manager) RemoveDeletedUsers() error {
  674. if _, err := a.db.Exec(deleteUsersMarkedQuery, time.Now().Unix()); err != nil {
  675. return err
  676. }
  677. return nil
  678. }
  679. // ChangeSettings persists the user settings
  680. func (a *Manager) ChangeSettings(userID string, prefs *Prefs) error {
  681. b, err := json.Marshal(prefs)
  682. if err != nil {
  683. return err
  684. }
  685. if _, err := a.db.Exec(updateUserPrefsQuery, string(b), userID); err != nil {
  686. return err
  687. }
  688. return nil
  689. }
  690. // ResetStats resets all user stats in the user database. This touches all users.
  691. func (a *Manager) ResetStats() error {
  692. a.mu.Lock() // Includes database query to avoid races!
  693. defer a.mu.Unlock()
  694. if _, err := a.db.Exec(updateUserStatsResetAllQuery); err != nil {
  695. return err
  696. }
  697. a.statsQueue = make(map[string]*Stats)
  698. return nil
  699. }
  700. // EnqueueUserStats adds the user to a queue which writes out user stats (messages, emails, ..) in
  701. // batches at a regular interval
  702. func (a *Manager) EnqueueUserStats(userID string, stats *Stats) {
  703. a.mu.Lock()
  704. defer a.mu.Unlock()
  705. a.statsQueue[userID] = stats
  706. }
  707. // EnqueueTokenUpdate adds the token update to a queue which writes out token access times
  708. // in batches at a regular interval
  709. func (a *Manager) EnqueueTokenUpdate(tokenID string, update *TokenUpdate) {
  710. a.mu.Lock()
  711. defer a.mu.Unlock()
  712. a.tokenQueue[tokenID] = update
  713. }
  714. func (a *Manager) asyncQueueWriter(interval time.Duration) {
  715. ticker := time.NewTicker(interval)
  716. for range ticker.C {
  717. if err := a.writeUserStatsQueue(); err != nil {
  718. log.Tag(tag).Err(err).Warn("Writing user stats queue failed")
  719. }
  720. if err := a.writeTokenUpdateQueue(); err != nil {
  721. log.Tag(tag).Err(err).Warn("Writing token update queue failed")
  722. }
  723. }
  724. }
  725. func (a *Manager) writeUserStatsQueue() error {
  726. a.mu.Lock()
  727. if len(a.statsQueue) == 0 {
  728. a.mu.Unlock()
  729. log.Tag(tag).Trace("No user stats updates to commit")
  730. return nil
  731. }
  732. statsQueue := a.statsQueue
  733. a.statsQueue = make(map[string]*Stats)
  734. a.mu.Unlock()
  735. tx, err := a.db.Begin()
  736. if err != nil {
  737. return err
  738. }
  739. defer tx.Rollback()
  740. log.Tag(tag).Debug("Writing user stats queue for %d user(s)", len(statsQueue))
  741. for userID, update := range statsQueue {
  742. log.
  743. Tag(tag).
  744. Fields(log.Context{
  745. "user_id": userID,
  746. "messages_count": update.Messages,
  747. "emails_count": update.Emails,
  748. "calls_count": update.Calls,
  749. }).
  750. Trace("Updating stats for user %s", userID)
  751. if _, err := tx.Exec(updateUserStatsQuery, update.Messages, update.Emails, update.Calls, userID); err != nil {
  752. return err
  753. }
  754. }
  755. return tx.Commit()
  756. }
  757. func (a *Manager) writeTokenUpdateQueue() error {
  758. a.mu.Lock()
  759. if len(a.tokenQueue) == 0 {
  760. a.mu.Unlock()
  761. log.Tag(tag).Trace("No token updates to commit")
  762. return nil
  763. }
  764. tokenQueue := a.tokenQueue
  765. a.tokenQueue = make(map[string]*TokenUpdate)
  766. a.mu.Unlock()
  767. tx, err := a.db.Begin()
  768. if err != nil {
  769. return err
  770. }
  771. defer tx.Rollback()
  772. log.Tag(tag).Debug("Writing token update queue for %d token(s)", len(tokenQueue))
  773. for tokenID, update := range tokenQueue {
  774. log.Tag(tag).Trace("Updating token %s with last access time %v", tokenID, update.LastAccess.Unix())
  775. if _, err := tx.Exec(updateTokenLastAccessQuery, update.LastAccess.Unix(), update.LastOrigin.String(), tokenID); err != nil {
  776. return err
  777. }
  778. }
  779. return tx.Commit()
  780. }
  781. // Authorize returns nil if the given user has access to the given topic using the desired
  782. // permission. The user param may be nil to signal an anonymous user.
  783. func (a *Manager) Authorize(user *User, topic string, perm Permission) error {
  784. if user != nil && user.Role == RoleAdmin {
  785. return nil // Admin can do everything
  786. }
  787. username := Everyone
  788. if user != nil {
  789. username = user.Name
  790. }
  791. // Select the read/write permissions for this user/topic combo.
  792. // - The query may return two rows (one for everyone, and one for the user), but prioritizes the user.
  793. // - Furthermore, the query prioritizes more specific permissions (longer!) over more generic ones, e.g. "test*" > "*"
  794. // - It also prioritizes write permissions over read permissions
  795. rows, err := a.db.Query(selectTopicPermsQuery, Everyone, username, topic)
  796. if err != nil {
  797. return err
  798. }
  799. defer rows.Close()
  800. if !rows.Next() {
  801. return a.resolvePerms(a.defaultAccess, perm)
  802. }
  803. var read, write bool
  804. if err := rows.Scan(&read, &write); err != nil {
  805. return err
  806. } else if err := rows.Err(); err != nil {
  807. return err
  808. }
  809. return a.resolvePerms(NewPermission(read, write), perm)
  810. }
  811. func (a *Manager) resolvePerms(base, perm Permission) error {
  812. if perm == PermissionRead && base.IsRead() {
  813. return nil
  814. } else if perm == PermissionWrite && base.IsWrite() {
  815. return nil
  816. }
  817. return ErrUnauthorized
  818. }
  819. // AddUser adds a user with the given username, password and role
  820. func (a *Manager) AddUser(username, password string, role Role) error {
  821. if !AllowedUsername(username) || !AllowedRole(role) {
  822. return ErrInvalidArgument
  823. }
  824. hash, err := bcrypt.GenerateFromPassword([]byte(password), a.bcryptCost)
  825. if err != nil {
  826. return err
  827. }
  828. userID := util.RandomStringPrefix(userIDPrefix, userIDLength)
  829. syncTopic, now := util.RandomStringPrefix(syncTopicPrefix, syncTopicLength), time.Now().Unix()
  830. if _, err = a.db.Exec(insertUserQuery, userID, username, hash, role, syncTopic, now); err != nil {
  831. if sqliteErr, ok := err.(sqlite3.Error); ok && sqliteErr.ExtendedCode == sqlite3.ErrConstraintUnique {
  832. return ErrUserExists
  833. }
  834. return err
  835. }
  836. return nil
  837. }
  838. // RemoveUser deletes the user with the given username. The function returns nil on success, even
  839. // if the user did not exist in the first place.
  840. func (a *Manager) RemoveUser(username string) error {
  841. if !AllowedUsername(username) {
  842. return ErrInvalidArgument
  843. }
  844. // Rows in user_access, user_token, etc. are deleted via foreign keys
  845. if _, err := a.db.Exec(deleteUserQuery, username); err != nil {
  846. return err
  847. }
  848. return nil
  849. }
  850. // MarkUserRemoved sets the deleted flag on the user, and deletes all access tokens. This prevents
  851. // successful auth via Authenticate. A background process will delete the user at a later date.
  852. func (a *Manager) MarkUserRemoved(user *User) error {
  853. if !AllowedUsername(user.Name) {
  854. return ErrInvalidArgument
  855. }
  856. tx, err := a.db.Begin()
  857. if err != nil {
  858. return err
  859. }
  860. defer tx.Rollback()
  861. if _, err := tx.Exec(deleteUserAccessQuery, user.Name, user.Name); err != nil {
  862. return err
  863. }
  864. if _, err := tx.Exec(deleteAllTokenQuery, user.ID); err != nil {
  865. return err
  866. }
  867. if _, err := tx.Exec(updateUserDeletedQuery, time.Now().Add(userHardDeleteAfterDuration).Unix(), user.ID); err != nil {
  868. return err
  869. }
  870. return tx.Commit()
  871. }
  872. // Users returns a list of users. It always also returns the Everyone user ("*").
  873. func (a *Manager) Users() ([]*User, error) {
  874. rows, err := a.db.Query(selectUsernamesQuery)
  875. if err != nil {
  876. return nil, err
  877. }
  878. defer rows.Close()
  879. usernames := make([]string, 0)
  880. for rows.Next() {
  881. var username string
  882. if err := rows.Scan(&username); err != nil {
  883. return nil, err
  884. } else if err := rows.Err(); err != nil {
  885. return nil, err
  886. }
  887. usernames = append(usernames, username)
  888. }
  889. rows.Close()
  890. users := make([]*User, 0)
  891. for _, username := range usernames {
  892. user, err := a.User(username)
  893. if err != nil {
  894. return nil, err
  895. }
  896. users = append(users, user)
  897. }
  898. return users, nil
  899. }
  900. // UsersCount returns the number of users in the databsae
  901. func (a *Manager) UsersCount() (int64, error) {
  902. rows, err := a.db.Query(selectUserCountQuery)
  903. if err != nil {
  904. return 0, err
  905. }
  906. defer rows.Close()
  907. if !rows.Next() {
  908. return 0, errNoRows
  909. }
  910. var count int64
  911. if err := rows.Scan(&count); err != nil {
  912. return 0, err
  913. }
  914. return count, nil
  915. }
  916. // User returns the user with the given username if it exists, or ErrUserNotFound otherwise.
  917. // You may also pass Everyone to retrieve the anonymous user and its Grant list.
  918. func (a *Manager) User(username string) (*User, error) {
  919. rows, err := a.db.Query(selectUserByNameQuery, username)
  920. if err != nil {
  921. return nil, err
  922. }
  923. return a.readUser(rows)
  924. }
  925. // UserByID returns the user with the given ID if it exists, or ErrUserNotFound otherwise
  926. func (a *Manager) UserByID(id string) (*User, error) {
  927. rows, err := a.db.Query(selectUserByIDQuery, id)
  928. if err != nil {
  929. return nil, err
  930. }
  931. return a.readUser(rows)
  932. }
  933. // UserByStripeCustomer returns the user with the given Stripe customer ID if it exists, or ErrUserNotFound otherwise.
  934. func (a *Manager) UserByStripeCustomer(stripeCustomerID string) (*User, error) {
  935. rows, err := a.db.Query(selectUserByStripeCustomerIDQuery, stripeCustomerID)
  936. if err != nil {
  937. return nil, err
  938. }
  939. return a.readUser(rows)
  940. }
  941. func (a *Manager) userByToken(token string) (*User, error) {
  942. rows, err := a.db.Query(selectUserByTokenQuery, token, time.Now().Unix())
  943. if err != nil {
  944. return nil, err
  945. }
  946. return a.readUser(rows)
  947. }
  948. func (a *Manager) readUser(rows *sql.Rows) (*User, error) {
  949. defer rows.Close()
  950. var id, username, hash, role, prefs, syncTopic string
  951. var stripeCustomerID, stripeSubscriptionID, stripeSubscriptionStatus, stripeSubscriptionInterval, stripeMonthlyPriceID, stripeYearlyPriceID, tierID, tierCode, tierName sql.NullString
  952. var messages, emails, calls int64
  953. var messagesLimit, messagesExpiryDuration, emailsLimit, callsLimit, reservationsLimit, attachmentFileSizeLimit, attachmentTotalSizeLimit, attachmentExpiryDuration, attachmentBandwidthLimit, stripeSubscriptionPaidUntil, stripeSubscriptionCancelAt, deleted sql.NullInt64
  954. if !rows.Next() {
  955. return nil, ErrUserNotFound
  956. }
  957. if err := rows.Scan(&id, &username, &hash, &role, &prefs, &syncTopic, &messages, &emails, &calls, &stripeCustomerID, &stripeSubscriptionID, &stripeSubscriptionStatus, &stripeSubscriptionInterval, &stripeSubscriptionPaidUntil, &stripeSubscriptionCancelAt, &deleted, &tierID, &tierCode, &tierName, &messagesLimit, &messagesExpiryDuration, &emailsLimit, &callsLimit, &reservationsLimit, &attachmentFileSizeLimit, &attachmentTotalSizeLimit, &attachmentExpiryDuration, &attachmentBandwidthLimit, &stripeMonthlyPriceID, &stripeYearlyPriceID); err != nil {
  958. return nil, err
  959. } else if err := rows.Err(); err != nil {
  960. return nil, err
  961. }
  962. user := &User{
  963. ID: id,
  964. Name: username,
  965. Hash: hash,
  966. Role: Role(role),
  967. Prefs: &Prefs{},
  968. SyncTopic: syncTopic,
  969. Stats: &Stats{
  970. Messages: messages,
  971. Emails: emails,
  972. Calls: calls,
  973. },
  974. Billing: &Billing{
  975. StripeCustomerID: stripeCustomerID.String, // May be empty
  976. StripeSubscriptionID: stripeSubscriptionID.String, // May be empty
  977. StripeSubscriptionStatus: stripe.SubscriptionStatus(stripeSubscriptionStatus.String), // May be empty
  978. StripeSubscriptionInterval: stripe.PriceRecurringInterval(stripeSubscriptionInterval.String), // May be empty
  979. StripeSubscriptionPaidUntil: time.Unix(stripeSubscriptionPaidUntil.Int64, 0), // May be zero
  980. StripeSubscriptionCancelAt: time.Unix(stripeSubscriptionCancelAt.Int64, 0), // May be zero
  981. },
  982. Deleted: deleted.Valid,
  983. }
  984. if err := json.Unmarshal([]byte(prefs), user.Prefs); err != nil {
  985. return nil, err
  986. }
  987. if tierCode.Valid {
  988. // See readTier() when this is changed!
  989. user.Tier = &Tier{
  990. ID: tierID.String,
  991. Code: tierCode.String,
  992. Name: tierName.String,
  993. MessageLimit: messagesLimit.Int64,
  994. MessageExpiryDuration: time.Duration(messagesExpiryDuration.Int64) * time.Second,
  995. EmailLimit: emailsLimit.Int64,
  996. CallLimit: callsLimit.Int64,
  997. ReservationLimit: reservationsLimit.Int64,
  998. AttachmentFileSizeLimit: attachmentFileSizeLimit.Int64,
  999. AttachmentTotalSizeLimit: attachmentTotalSizeLimit.Int64,
  1000. AttachmentExpiryDuration: time.Duration(attachmentExpiryDuration.Int64) * time.Second,
  1001. AttachmentBandwidthLimit: attachmentBandwidthLimit.Int64,
  1002. StripeMonthlyPriceID: stripeMonthlyPriceID.String, // May be empty
  1003. StripeYearlyPriceID: stripeYearlyPriceID.String, // May be empty
  1004. }
  1005. }
  1006. return user, nil
  1007. }
  1008. // AllGrants returns all user-specific access control entries, mapped to their respective user IDs
  1009. func (a *Manager) AllGrants() (map[string][]Grant, error) {
  1010. rows, err := a.db.Query(selectUserAllAccessQuery)
  1011. if err != nil {
  1012. return nil, err
  1013. }
  1014. defer rows.Close()
  1015. grants := make(map[string][]Grant, 0)
  1016. for rows.Next() {
  1017. var userID, topic string
  1018. var read, write bool
  1019. if err := rows.Scan(&userID, &topic, &read, &write); err != nil {
  1020. return nil, err
  1021. } else if err := rows.Err(); err != nil {
  1022. return nil, err
  1023. }
  1024. if _, ok := grants[userID]; !ok {
  1025. grants[userID] = make([]Grant, 0)
  1026. }
  1027. grants[userID] = append(grants[userID], Grant{
  1028. TopicPattern: fromSQLWildcard(topic),
  1029. Allow: NewPermission(read, write),
  1030. })
  1031. }
  1032. return grants, nil
  1033. }
  1034. // Grants returns all user-specific access control entries
  1035. func (a *Manager) Grants(username string) ([]Grant, error) {
  1036. rows, err := a.db.Query(selectUserAccessQuery, username)
  1037. if err != nil {
  1038. return nil, err
  1039. }
  1040. defer rows.Close()
  1041. grants := make([]Grant, 0)
  1042. for rows.Next() {
  1043. var topic string
  1044. var read, write bool
  1045. if err := rows.Scan(&topic, &read, &write); err != nil {
  1046. return nil, err
  1047. } else if err := rows.Err(); err != nil {
  1048. return nil, err
  1049. }
  1050. grants = append(grants, Grant{
  1051. TopicPattern: fromSQLWildcard(topic),
  1052. Allow: NewPermission(read, write),
  1053. })
  1054. }
  1055. return grants, nil
  1056. }
  1057. // Reservations returns all user-owned topics, and the associated everyone-access
  1058. func (a *Manager) Reservations(username string) ([]Reservation, error) {
  1059. rows, err := a.db.Query(selectUserReservationsQuery, Everyone, username)
  1060. if err != nil {
  1061. return nil, err
  1062. }
  1063. defer rows.Close()
  1064. reservations := make([]Reservation, 0)
  1065. for rows.Next() {
  1066. var topic string
  1067. var ownerRead, ownerWrite bool
  1068. var everyoneRead, everyoneWrite sql.NullBool
  1069. if err := rows.Scan(&topic, &ownerRead, &ownerWrite, &everyoneRead, &everyoneWrite); err != nil {
  1070. return nil, err
  1071. } else if err := rows.Err(); err != nil {
  1072. return nil, err
  1073. }
  1074. reservations = append(reservations, Reservation{
  1075. Topic: unescapeUnderscore(topic),
  1076. Owner: NewPermission(ownerRead, ownerWrite),
  1077. Everyone: NewPermission(everyoneRead.Bool, everyoneWrite.Bool), // false if null
  1078. })
  1079. }
  1080. return reservations, nil
  1081. }
  1082. // HasReservation returns true if the given topic access is owned by the user
  1083. func (a *Manager) HasReservation(username, topic string) (bool, error) {
  1084. rows, err := a.db.Query(selectUserHasReservationQuery, username, escapeUnderscore(topic))
  1085. if err != nil {
  1086. return false, err
  1087. }
  1088. defer rows.Close()
  1089. if !rows.Next() {
  1090. return false, errNoRows
  1091. }
  1092. var count int64
  1093. if err := rows.Scan(&count); err != nil {
  1094. return false, err
  1095. }
  1096. return count > 0, nil
  1097. }
  1098. // ReservationsCount returns the number of reservations owned by this user
  1099. func (a *Manager) ReservationsCount(username string) (int64, error) {
  1100. rows, err := a.db.Query(selectUserReservationsCountQuery, username)
  1101. if err != nil {
  1102. return 0, err
  1103. }
  1104. defer rows.Close()
  1105. if !rows.Next() {
  1106. return 0, errNoRows
  1107. }
  1108. var count int64
  1109. if err := rows.Scan(&count); err != nil {
  1110. return 0, err
  1111. }
  1112. return count, nil
  1113. }
  1114. // ReservationOwner returns user ID of the user that owns this topic, or an
  1115. // empty string if it's not owned by anyone
  1116. func (a *Manager) ReservationOwner(topic string) (string, error) {
  1117. rows, err := a.db.Query(selectUserReservationsOwnerQuery, escapeUnderscore(topic))
  1118. if err != nil {
  1119. return "", err
  1120. }
  1121. defer rows.Close()
  1122. if !rows.Next() {
  1123. return "", nil
  1124. }
  1125. var ownerUserID string
  1126. if err := rows.Scan(&ownerUserID); err != nil {
  1127. return "", err
  1128. }
  1129. return ownerUserID, nil
  1130. }
  1131. // ChangePassword changes a user's password
  1132. func (a *Manager) ChangePassword(username, password string) error {
  1133. hash, err := bcrypt.GenerateFromPassword([]byte(password), a.bcryptCost)
  1134. if err != nil {
  1135. return err
  1136. }
  1137. if _, err := a.db.Exec(updateUserPassQuery, hash, username); err != nil {
  1138. return err
  1139. }
  1140. return nil
  1141. }
  1142. // ChangeRole changes a user's role. When a role is changed from RoleUser to RoleAdmin,
  1143. // all existing access control entries (Grant) are removed, since they are no longer needed.
  1144. func (a *Manager) ChangeRole(username string, role Role) error {
  1145. if !AllowedUsername(username) || !AllowedRole(role) {
  1146. return ErrInvalidArgument
  1147. }
  1148. if _, err := a.db.Exec(updateUserRoleQuery, string(role), username); err != nil {
  1149. return err
  1150. }
  1151. if role == RoleAdmin {
  1152. if _, err := a.db.Exec(deleteUserAccessQuery, username, username); err != nil {
  1153. return err
  1154. }
  1155. }
  1156. return nil
  1157. }
  1158. // ChangeTier changes a user's tier using the tier code. This function does not delete reservations, messages,
  1159. // or attachments, even if the new tier has lower limits in this regard. That has to be done elsewhere.
  1160. func (a *Manager) ChangeTier(username, tier string) error {
  1161. if !AllowedUsername(username) {
  1162. return ErrInvalidArgument
  1163. }
  1164. t, err := a.Tier(tier)
  1165. if err != nil {
  1166. return err
  1167. } else if err := a.checkReservationsLimit(username, t.ReservationLimit); err != nil {
  1168. return err
  1169. }
  1170. if _, err := a.db.Exec(updateUserTierQuery, tier, username); err != nil {
  1171. return err
  1172. }
  1173. return nil
  1174. }
  1175. // ResetTier removes the tier from the given user
  1176. func (a *Manager) ResetTier(username string) error {
  1177. if !AllowedUsername(username) && username != Everyone && username != "" {
  1178. return ErrInvalidArgument
  1179. } else if err := a.checkReservationsLimit(username, 0); err != nil {
  1180. return err
  1181. }
  1182. _, err := a.db.Exec(deleteUserTierQuery, username)
  1183. return err
  1184. }
  1185. func (a *Manager) checkReservationsLimit(username string, reservationsLimit int64) error {
  1186. u, err := a.User(username)
  1187. if err != nil {
  1188. return err
  1189. }
  1190. if u.Tier != nil && reservationsLimit < u.Tier.ReservationLimit {
  1191. reservations, err := a.Reservations(username)
  1192. if err != nil {
  1193. return err
  1194. } else if int64(len(reservations)) > reservationsLimit {
  1195. return ErrTooManyReservations
  1196. }
  1197. }
  1198. return nil
  1199. }
  1200. // AllowReservation tests if a user may create an access control entry for the given topic.
  1201. // If there are any ACL entries that are not owned by the user, an error is returned.
  1202. func (a *Manager) AllowReservation(username string, topic string) error {
  1203. if (!AllowedUsername(username) && username != Everyone) || !AllowedTopic(topic) {
  1204. return ErrInvalidArgument
  1205. }
  1206. rows, err := a.db.Query(selectOtherAccessCountQuery, escapeUnderscore(topic), escapeUnderscore(topic), username)
  1207. if err != nil {
  1208. return err
  1209. }
  1210. defer rows.Close()
  1211. if !rows.Next() {
  1212. return errNoRows
  1213. }
  1214. var otherCount int
  1215. if err := rows.Scan(&otherCount); err != nil {
  1216. return err
  1217. }
  1218. if otherCount > 0 {
  1219. return errTopicOwnedByOthers
  1220. }
  1221. return nil
  1222. }
  1223. // AllowAccess adds or updates an entry in th access control list for a specific user. It controls
  1224. // read/write access to a topic. The parameter topicPattern may include wildcards (*). The ACL entry
  1225. // owner may either be a user (username), or the system (empty).
  1226. func (a *Manager) AllowAccess(username string, topicPattern string, permission Permission) error {
  1227. if !AllowedUsername(username) && username != Everyone {
  1228. return ErrInvalidArgument
  1229. } else if !AllowedTopicPattern(topicPattern) {
  1230. return ErrInvalidArgument
  1231. }
  1232. owner := ""
  1233. if _, err := a.db.Exec(upsertUserAccessQuery, username, toSQLWildcard(topicPattern), permission.IsRead(), permission.IsWrite(), owner, owner); err != nil {
  1234. return err
  1235. }
  1236. return nil
  1237. }
  1238. // ResetAccess removes an access control list entry for a specific username/topic, or (if topic is
  1239. // empty) for an entire user. The parameter topicPattern may include wildcards (*).
  1240. func (a *Manager) ResetAccess(username string, topicPattern string) error {
  1241. if !AllowedUsername(username) && username != Everyone && username != "" {
  1242. return ErrInvalidArgument
  1243. } else if !AllowedTopicPattern(topicPattern) && topicPattern != "" {
  1244. return ErrInvalidArgument
  1245. }
  1246. if username == "" && topicPattern == "" {
  1247. _, err := a.db.Exec(deleteAllAccessQuery, username)
  1248. return err
  1249. } else if topicPattern == "" {
  1250. _, err := a.db.Exec(deleteUserAccessQuery, username, username)
  1251. return err
  1252. }
  1253. _, err := a.db.Exec(deleteTopicAccessQuery, username, username, toSQLWildcard(topicPattern))
  1254. return err
  1255. }
  1256. // AddReservation creates two access control entries for the given topic: one with full read/write access for the
  1257. // given user, and one for Everyone with the permission passed as everyone. The user also owns the entries, and
  1258. // can modify or delete them.
  1259. func (a *Manager) AddReservation(username string, topic string, everyone Permission) error {
  1260. if !AllowedUsername(username) || username == Everyone || !AllowedTopic(topic) {
  1261. return ErrInvalidArgument
  1262. }
  1263. tx, err := a.db.Begin()
  1264. if err != nil {
  1265. return err
  1266. }
  1267. defer tx.Rollback()
  1268. if _, err := tx.Exec(upsertUserAccessQuery, username, escapeUnderscore(topic), true, true, username, username); err != nil {
  1269. return err
  1270. }
  1271. if _, err := tx.Exec(upsertUserAccessQuery, Everyone, escapeUnderscore(topic), everyone.IsRead(), everyone.IsWrite(), username, username); err != nil {
  1272. return err
  1273. }
  1274. return tx.Commit()
  1275. }
  1276. // RemoveReservations deletes the access control entries associated with the given username/topic, as
  1277. // well as all entries with Everyone/topic. This is the counterpart for AddReservation.
  1278. func (a *Manager) RemoveReservations(username string, topics ...string) error {
  1279. if !AllowedUsername(username) || username == Everyone || len(topics) == 0 {
  1280. return ErrInvalidArgument
  1281. }
  1282. for _, topic := range topics {
  1283. if !AllowedTopic(topic) {
  1284. return ErrInvalidArgument
  1285. }
  1286. }
  1287. tx, err := a.db.Begin()
  1288. if err != nil {
  1289. return err
  1290. }
  1291. defer tx.Rollback()
  1292. for _, topic := range topics {
  1293. if _, err := tx.Exec(deleteTopicAccessQuery, username, username, escapeUnderscore(topic)); err != nil {
  1294. return err
  1295. }
  1296. if _, err := tx.Exec(deleteTopicAccessQuery, Everyone, Everyone, escapeUnderscore(topic)); err != nil {
  1297. return err
  1298. }
  1299. }
  1300. return tx.Commit()
  1301. }
  1302. // DefaultAccess returns the default read/write access if no access control entry matches
  1303. func (a *Manager) DefaultAccess() Permission {
  1304. return a.defaultAccess
  1305. }
  1306. // AddTier creates a new tier in the database
  1307. func (a *Manager) AddTier(tier *Tier) error {
  1308. if tier.ID == "" {
  1309. tier.ID = util.RandomStringPrefix(tierIDPrefix, tierIDLength)
  1310. }
  1311. if _, err := a.db.Exec(insertTierQuery, tier.ID, tier.Code, tier.Name, tier.MessageLimit, int64(tier.MessageExpiryDuration.Seconds()), tier.EmailLimit, tier.CallLimit, tier.ReservationLimit, tier.AttachmentFileSizeLimit, tier.AttachmentTotalSizeLimit, int64(tier.AttachmentExpiryDuration.Seconds()), tier.AttachmentBandwidthLimit, nullString(tier.StripeMonthlyPriceID), nullString(tier.StripeYearlyPriceID)); err != nil {
  1312. return err
  1313. }
  1314. return nil
  1315. }
  1316. // UpdateTier updates a tier's properties in the database
  1317. func (a *Manager) UpdateTier(tier *Tier) error {
  1318. if _, err := a.db.Exec(updateTierQuery, tier.Name, tier.MessageLimit, int64(tier.MessageExpiryDuration.Seconds()), tier.EmailLimit, tier.CallLimit, tier.ReservationLimit, tier.AttachmentFileSizeLimit, tier.AttachmentTotalSizeLimit, int64(tier.AttachmentExpiryDuration.Seconds()), tier.AttachmentBandwidthLimit, nullString(tier.StripeMonthlyPriceID), nullString(tier.StripeYearlyPriceID), tier.Code); err != nil {
  1319. return err
  1320. }
  1321. return nil
  1322. }
  1323. // RemoveTier deletes the tier with the given code
  1324. func (a *Manager) RemoveTier(code string) error {
  1325. if !AllowedTier(code) {
  1326. return ErrInvalidArgument
  1327. }
  1328. // This fails if any user has this tier
  1329. if _, err := a.db.Exec(deleteTierQuery, code); err != nil {
  1330. return err
  1331. }
  1332. return nil
  1333. }
  1334. // ChangeBilling updates a user's billing fields, namely the Stripe customer ID, and subscription information
  1335. func (a *Manager) ChangeBilling(username string, billing *Billing) error {
  1336. if _, err := a.db.Exec(updateBillingQuery, nullString(billing.StripeCustomerID), nullString(billing.StripeSubscriptionID), nullString(string(billing.StripeSubscriptionStatus)), nullString(string(billing.StripeSubscriptionInterval)), nullInt64(billing.StripeSubscriptionPaidUntil.Unix()), nullInt64(billing.StripeSubscriptionCancelAt.Unix()), username); err != nil {
  1337. return err
  1338. }
  1339. return nil
  1340. }
  1341. // Tiers returns a list of all Tier structs
  1342. func (a *Manager) Tiers() ([]*Tier, error) {
  1343. rows, err := a.db.Query(selectTiersQuery)
  1344. if err != nil {
  1345. return nil, err
  1346. }
  1347. defer rows.Close()
  1348. tiers := make([]*Tier, 0)
  1349. for {
  1350. tier, err := a.readTier(rows)
  1351. if err == ErrTierNotFound {
  1352. break
  1353. } else if err != nil {
  1354. return nil, err
  1355. }
  1356. tiers = append(tiers, tier)
  1357. }
  1358. return tiers, nil
  1359. }
  1360. // Tier returns a Tier based on the code, or ErrTierNotFound if it does not exist
  1361. func (a *Manager) Tier(code string) (*Tier, error) {
  1362. rows, err := a.db.Query(selectTierByCodeQuery, code)
  1363. if err != nil {
  1364. return nil, err
  1365. }
  1366. defer rows.Close()
  1367. return a.readTier(rows)
  1368. }
  1369. // TierByStripePrice returns a Tier based on the Stripe price ID, or ErrTierNotFound if it does not exist
  1370. func (a *Manager) TierByStripePrice(priceID string) (*Tier, error) {
  1371. rows, err := a.db.Query(selectTierByPriceIDQuery, priceID, priceID)
  1372. if err != nil {
  1373. return nil, err
  1374. }
  1375. defer rows.Close()
  1376. return a.readTier(rows)
  1377. }
  1378. func (a *Manager) readTier(rows *sql.Rows) (*Tier, error) {
  1379. var id, code, name string
  1380. var stripeMonthlyPriceID, stripeYearlyPriceID sql.NullString
  1381. var messagesLimit, messagesExpiryDuration, emailsLimit, callsLimit, reservationsLimit, attachmentFileSizeLimit, attachmentTotalSizeLimit, attachmentExpiryDuration, attachmentBandwidthLimit sql.NullInt64
  1382. if !rows.Next() {
  1383. return nil, ErrTierNotFound
  1384. }
  1385. if err := rows.Scan(&id, &code, &name, &messagesLimit, &messagesExpiryDuration, &emailsLimit, &callsLimit, &reservationsLimit, &attachmentFileSizeLimit, &attachmentTotalSizeLimit, &attachmentExpiryDuration, &attachmentBandwidthLimit, &stripeMonthlyPriceID, &stripeYearlyPriceID); err != nil {
  1386. return nil, err
  1387. } else if err := rows.Err(); err != nil {
  1388. return nil, err
  1389. }
  1390. // When changed, note readUser() as well
  1391. return &Tier{
  1392. ID: id,
  1393. Code: code,
  1394. Name: name,
  1395. MessageLimit: messagesLimit.Int64,
  1396. MessageExpiryDuration: time.Duration(messagesExpiryDuration.Int64) * time.Second,
  1397. EmailLimit: emailsLimit.Int64,
  1398. CallLimit: callsLimit.Int64,
  1399. ReservationLimit: reservationsLimit.Int64,
  1400. AttachmentFileSizeLimit: attachmentFileSizeLimit.Int64,
  1401. AttachmentTotalSizeLimit: attachmentTotalSizeLimit.Int64,
  1402. AttachmentExpiryDuration: time.Duration(attachmentExpiryDuration.Int64) * time.Second,
  1403. AttachmentBandwidthLimit: attachmentBandwidthLimit.Int64,
  1404. StripeMonthlyPriceID: stripeMonthlyPriceID.String, // May be empty
  1405. StripeYearlyPriceID: stripeYearlyPriceID.String, // May be empty
  1406. }, nil
  1407. }
  1408. // Close closes the underlying database
  1409. func (a *Manager) Close() error {
  1410. return a.db.Close()
  1411. }
  1412. // toSQLWildcard converts a wildcard string to a SQL wildcard string. It only allows '*' as wildcards,
  1413. // and escapes '_', assuming '\' as escape character.
  1414. func toSQLWildcard(s string) string {
  1415. return escapeUnderscore(strings.ReplaceAll(s, "*", "%"))
  1416. }
  1417. // fromSQLWildcard converts a SQL wildcard string to a wildcard string. It converts '%' to '*',
  1418. // and removes the '\_' escape character.
  1419. func fromSQLWildcard(s string) string {
  1420. return strings.ReplaceAll(unescapeUnderscore(s), "%", "*")
  1421. }
  1422. func escapeUnderscore(s string) string {
  1423. return strings.ReplaceAll(s, "_", "\\_")
  1424. }
  1425. func unescapeUnderscore(s string) string {
  1426. return strings.ReplaceAll(s, "\\_", "_")
  1427. }
  1428. func runStartupQueries(db *sql.DB, startupQueries string) error {
  1429. if _, err := db.Exec(startupQueries); err != nil {
  1430. return err
  1431. }
  1432. if _, err := db.Exec(builtinStartupQueries); err != nil {
  1433. return err
  1434. }
  1435. return nil
  1436. }
  1437. func setupDB(db *sql.DB) error {
  1438. // If 'schemaVersion' table does not exist, this must be a new database
  1439. rowsSV, err := db.Query(selectSchemaVersionQuery)
  1440. if err != nil {
  1441. return setupNewDB(db)
  1442. }
  1443. defer rowsSV.Close()
  1444. // If 'schemaVersion' table exists, read version and potentially upgrade
  1445. schemaVersion := 0
  1446. if !rowsSV.Next() {
  1447. return errors.New("cannot determine schema version: database file may be corrupt")
  1448. }
  1449. if err := rowsSV.Scan(&schemaVersion); err != nil {
  1450. return err
  1451. }
  1452. rowsSV.Close()
  1453. // Do migrations
  1454. if schemaVersion == currentSchemaVersion {
  1455. return nil
  1456. } else if schemaVersion > currentSchemaVersion {
  1457. return fmt.Errorf("unexpected schema version: version %d is higher than current version %d", schemaVersion, currentSchemaVersion)
  1458. }
  1459. for i := schemaVersion; i < currentSchemaVersion; i++ {
  1460. fn, ok := migrations[i]
  1461. if !ok {
  1462. return fmt.Errorf("cannot find migration step from schema version %d to %d", i, i+1)
  1463. } else if err := fn(db); err != nil {
  1464. return err
  1465. }
  1466. }
  1467. return nil
  1468. }
  1469. func setupNewDB(db *sql.DB) error {
  1470. if _, err := db.Exec(createTablesQueries); err != nil {
  1471. return err
  1472. }
  1473. if _, err := db.Exec(insertSchemaVersion, currentSchemaVersion); err != nil {
  1474. return err
  1475. }
  1476. return nil
  1477. }
  1478. func migrateFrom1(db *sql.DB) error {
  1479. log.Tag(tag).Info("Migrating user database schema: from 1 to 2")
  1480. tx, err := db.Begin()
  1481. if err != nil {
  1482. return err
  1483. }
  1484. defer tx.Rollback()
  1485. // Rename user -> user_old, and create new tables
  1486. if _, err := tx.Exec(migrate1To2CreateTablesQueries); err != nil {
  1487. return err
  1488. }
  1489. // Insert users from user_old into new user table, with ID and sync_topic
  1490. rows, err := tx.Query(migrate1To2SelectAllOldUsernamesNoTx)
  1491. if err != nil {
  1492. return err
  1493. }
  1494. defer rows.Close()
  1495. usernames := make([]string, 0)
  1496. for rows.Next() {
  1497. var username string
  1498. if err := rows.Scan(&username); err != nil {
  1499. return err
  1500. }
  1501. usernames = append(usernames, username)
  1502. }
  1503. if err := rows.Close(); err != nil {
  1504. return err
  1505. }
  1506. for _, username := range usernames {
  1507. userID := util.RandomStringPrefix(userIDPrefix, userIDLength)
  1508. syncTopic := util.RandomStringPrefix(syncTopicPrefix, syncTopicLength)
  1509. if _, err := tx.Exec(migrate1To2InsertUserNoTx, userID, syncTopic, username); err != nil {
  1510. return err
  1511. }
  1512. }
  1513. // Migrate old "access" table to "user_access" and drop "access" and "user_old"
  1514. if _, err := tx.Exec(migrate1To2InsertFromOldTablesAndDropNoTx); err != nil {
  1515. return err
  1516. }
  1517. if _, err := tx.Exec(updateSchemaVersion, 2); err != nil {
  1518. return err
  1519. }
  1520. if err := tx.Commit(); err != nil {
  1521. return err
  1522. }
  1523. return nil
  1524. }
  1525. func migrateFrom2(db *sql.DB) error {
  1526. log.Tag(tag).Info("Migrating user database schema: from 2 to 3")
  1527. tx, err := db.Begin()
  1528. if err != nil {
  1529. return err
  1530. }
  1531. defer tx.Rollback()
  1532. if _, err := tx.Exec(migrate2To3UpdateQueries); err != nil {
  1533. return err
  1534. }
  1535. if _, err := tx.Exec(updateSchemaVersion, 3); err != nil {
  1536. return err
  1537. }
  1538. return tx.Commit()
  1539. }
  1540. func migrateFrom3(db *sql.DB) error {
  1541. log.Tag(tag).Info("Migrating user database schema: from 3 to 4")
  1542. tx, err := db.Begin()
  1543. if err != nil {
  1544. return err
  1545. }
  1546. defer tx.Rollback()
  1547. if _, err := tx.Exec(migrate3To4UpdateQueries); err != nil {
  1548. return err
  1549. }
  1550. if _, err := tx.Exec(updateSchemaVersion, 4); err != nil {
  1551. return err
  1552. }
  1553. return tx.Commit()
  1554. }
  1555. func migrateFrom4(db *sql.DB) error {
  1556. log.Tag(tag).Info("Migrating user database schema: from 4 to 5")
  1557. tx, err := db.Begin()
  1558. if err != nil {
  1559. return err
  1560. }
  1561. defer tx.Rollback()
  1562. if _, err := tx.Exec(migrate4To5UpdateQueries); err != nil {
  1563. return err
  1564. }
  1565. if _, err := tx.Exec(updateSchemaVersion, 5); err != nil {
  1566. return err
  1567. }
  1568. return tx.Commit()
  1569. }
  1570. func nullString(s string) sql.NullString {
  1571. if s == "" {
  1572. return sql.NullString{}
  1573. }
  1574. return sql.NullString{String: s, Valid: true}
  1575. }
  1576. func nullInt64(v int64) sql.NullInt64 {
  1577. if v == 0 {
  1578. return sql.NullInt64{}
  1579. }
  1580. return sql.NullInt64{Int64: v, Valid: true}
  1581. }