manager.go 56 KB

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