manager.go 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676
  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 ESCAPE '\'
  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 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. The query may return two
  792. // rows (one for everyone, and one for the user), but prioritizes the user.
  793. rows, err := a.db.Query(selectTopicPermsQuery, Everyone, username, topic)
  794. if err != nil {
  795. return err
  796. }
  797. defer rows.Close()
  798. if !rows.Next() {
  799. return a.resolvePerms(a.defaultAccess, perm)
  800. }
  801. var read, write bool
  802. if err := rows.Scan(&read, &write); err != nil {
  803. return err
  804. } else if err := rows.Err(); err != nil {
  805. return err
  806. }
  807. return a.resolvePerms(NewPermission(read, write), perm)
  808. }
  809. func (a *Manager) resolvePerms(base, perm Permission) error {
  810. if perm == PermissionRead && base.IsRead() {
  811. return nil
  812. } else if perm == PermissionWrite && base.IsWrite() {
  813. return nil
  814. }
  815. return ErrUnauthorized
  816. }
  817. // AddUser adds a user with the given username, password and role
  818. func (a *Manager) AddUser(username, password string, role Role) error {
  819. if !AllowedUsername(username) || !AllowedRole(role) {
  820. return ErrInvalidArgument
  821. }
  822. hash, err := bcrypt.GenerateFromPassword([]byte(password), a.bcryptCost)
  823. if err != nil {
  824. return err
  825. }
  826. userID := util.RandomStringPrefix(userIDPrefix, userIDLength)
  827. syncTopic, now := util.RandomStringPrefix(syncTopicPrefix, syncTopicLength), time.Now().Unix()
  828. if _, err = a.db.Exec(insertUserQuery, userID, username, hash, role, syncTopic, now); err != nil {
  829. if sqliteErr, ok := err.(sqlite3.Error); ok && sqliteErr.ExtendedCode == sqlite3.ErrConstraintUnique {
  830. return ErrUserExists
  831. }
  832. return err
  833. }
  834. return nil
  835. }
  836. // RemoveUser deletes the user with the given username. The function returns nil on success, even
  837. // if the user did not exist in the first place.
  838. func (a *Manager) RemoveUser(username string) error {
  839. if !AllowedUsername(username) {
  840. return ErrInvalidArgument
  841. }
  842. // Rows in user_access, user_token, etc. are deleted via foreign keys
  843. if _, err := a.db.Exec(deleteUserQuery, username); err != nil {
  844. return err
  845. }
  846. return nil
  847. }
  848. // MarkUserRemoved sets the deleted flag on the user, and deletes all access tokens. This prevents
  849. // successful auth via Authenticate. A background process will delete the user at a later date.
  850. func (a *Manager) MarkUserRemoved(user *User) error {
  851. if !AllowedUsername(user.Name) {
  852. return ErrInvalidArgument
  853. }
  854. tx, err := a.db.Begin()
  855. if err != nil {
  856. return err
  857. }
  858. defer tx.Rollback()
  859. if _, err := tx.Exec(deleteUserAccessQuery, user.Name, user.Name); err != nil {
  860. return err
  861. }
  862. if _, err := tx.Exec(deleteAllTokenQuery, user.ID); err != nil {
  863. return err
  864. }
  865. if _, err := tx.Exec(updateUserDeletedQuery, time.Now().Add(userHardDeleteAfterDuration).Unix(), user.ID); err != nil {
  866. return err
  867. }
  868. return tx.Commit()
  869. }
  870. // Users returns a list of users. It always also returns the Everyone user ("*").
  871. func (a *Manager) Users() ([]*User, error) {
  872. rows, err := a.db.Query(selectUsernamesQuery)
  873. if err != nil {
  874. return nil, err
  875. }
  876. defer rows.Close()
  877. usernames := make([]string, 0)
  878. for rows.Next() {
  879. var username string
  880. if err := rows.Scan(&username); err != nil {
  881. return nil, err
  882. } else if err := rows.Err(); err != nil {
  883. return nil, err
  884. }
  885. usernames = append(usernames, username)
  886. }
  887. rows.Close()
  888. users := make([]*User, 0)
  889. for _, username := range usernames {
  890. user, err := a.User(username)
  891. if err != nil {
  892. return nil, err
  893. }
  894. users = append(users, user)
  895. }
  896. return users, nil
  897. }
  898. // UsersCount returns the number of users in the databsae
  899. func (a *Manager) UsersCount() (int64, error) {
  900. rows, err := a.db.Query(selectUserCountQuery)
  901. if err != nil {
  902. return 0, err
  903. }
  904. defer rows.Close()
  905. if !rows.Next() {
  906. return 0, errNoRows
  907. }
  908. var count int64
  909. if err := rows.Scan(&count); err != nil {
  910. return 0, err
  911. }
  912. return count, nil
  913. }
  914. // User returns the user with the given username if it exists, or ErrUserNotFound otherwise.
  915. // You may also pass Everyone to retrieve the anonymous user and its Grant list.
  916. func (a *Manager) User(username string) (*User, error) {
  917. rows, err := a.db.Query(selectUserByNameQuery, username)
  918. if err != nil {
  919. return nil, err
  920. }
  921. return a.readUser(rows)
  922. }
  923. // UserByID returns the user with the given ID if it exists, or ErrUserNotFound otherwise
  924. func (a *Manager) UserByID(id string) (*User, error) {
  925. rows, err := a.db.Query(selectUserByIDQuery, id)
  926. if err != nil {
  927. return nil, err
  928. }
  929. return a.readUser(rows)
  930. }
  931. // UserByStripeCustomer returns the user with the given Stripe customer ID if it exists, or ErrUserNotFound otherwise.
  932. func (a *Manager) UserByStripeCustomer(stripeCustomerID string) (*User, error) {
  933. rows, err := a.db.Query(selectUserByStripeCustomerIDQuery, stripeCustomerID)
  934. if err != nil {
  935. return nil, err
  936. }
  937. return a.readUser(rows)
  938. }
  939. func (a *Manager) userByToken(token string) (*User, error) {
  940. rows, err := a.db.Query(selectUserByTokenQuery, token, time.Now().Unix())
  941. if err != nil {
  942. return nil, err
  943. }
  944. return a.readUser(rows)
  945. }
  946. func (a *Manager) readUser(rows *sql.Rows) (*User, error) {
  947. defer rows.Close()
  948. var id, username, hash, role, prefs, syncTopic string
  949. var stripeCustomerID, stripeSubscriptionID, stripeSubscriptionStatus, stripeSubscriptionInterval, stripeMonthlyPriceID, stripeYearlyPriceID, tierID, tierCode, tierName sql.NullString
  950. var messages, emails, calls int64
  951. var messagesLimit, messagesExpiryDuration, emailsLimit, callsLimit, reservationsLimit, attachmentFileSizeLimit, attachmentTotalSizeLimit, attachmentExpiryDuration, attachmentBandwidthLimit, stripeSubscriptionPaidUntil, stripeSubscriptionCancelAt, deleted sql.NullInt64
  952. if !rows.Next() {
  953. return nil, ErrUserNotFound
  954. }
  955. 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 {
  956. return nil, err
  957. } else if err := rows.Err(); err != nil {
  958. return nil, err
  959. }
  960. user := &User{
  961. ID: id,
  962. Name: username,
  963. Hash: hash,
  964. Role: Role(role),
  965. Prefs: &Prefs{},
  966. SyncTopic: syncTopic,
  967. Stats: &Stats{
  968. Messages: messages,
  969. Emails: emails,
  970. Calls: calls,
  971. },
  972. Billing: &Billing{
  973. StripeCustomerID: stripeCustomerID.String, // May be empty
  974. StripeSubscriptionID: stripeSubscriptionID.String, // May be empty
  975. StripeSubscriptionStatus: stripe.SubscriptionStatus(stripeSubscriptionStatus.String), // May be empty
  976. StripeSubscriptionInterval: stripe.PriceRecurringInterval(stripeSubscriptionInterval.String), // May be empty
  977. StripeSubscriptionPaidUntil: time.Unix(stripeSubscriptionPaidUntil.Int64, 0), // May be zero
  978. StripeSubscriptionCancelAt: time.Unix(stripeSubscriptionCancelAt.Int64, 0), // May be zero
  979. },
  980. Deleted: deleted.Valid,
  981. }
  982. if err := json.Unmarshal([]byte(prefs), user.Prefs); err != nil {
  983. return nil, err
  984. }
  985. if tierCode.Valid {
  986. // See readTier() when this is changed!
  987. user.Tier = &Tier{
  988. ID: tierID.String,
  989. Code: tierCode.String,
  990. Name: tierName.String,
  991. MessageLimit: messagesLimit.Int64,
  992. MessageExpiryDuration: time.Duration(messagesExpiryDuration.Int64) * time.Second,
  993. EmailLimit: emailsLimit.Int64,
  994. CallLimit: callsLimit.Int64,
  995. ReservationLimit: reservationsLimit.Int64,
  996. AttachmentFileSizeLimit: attachmentFileSizeLimit.Int64,
  997. AttachmentTotalSizeLimit: attachmentTotalSizeLimit.Int64,
  998. AttachmentExpiryDuration: time.Duration(attachmentExpiryDuration.Int64) * time.Second,
  999. AttachmentBandwidthLimit: attachmentBandwidthLimit.Int64,
  1000. StripeMonthlyPriceID: stripeMonthlyPriceID.String, // May be empty
  1001. StripeYearlyPriceID: stripeYearlyPriceID.String, // May be empty
  1002. }
  1003. }
  1004. return user, nil
  1005. }
  1006. // AllGrants returns all user-specific access control entries, mapped to their respective user IDs
  1007. func (a *Manager) AllGrants() (map[string][]Grant, error) {
  1008. rows, err := a.db.Query(selectUserAllAccessQuery)
  1009. if err != nil {
  1010. return nil, err
  1011. }
  1012. defer rows.Close()
  1013. grants := make(map[string][]Grant, 0)
  1014. for rows.Next() {
  1015. var userID, topic string
  1016. var read, write bool
  1017. if err := rows.Scan(&userID, &topic, &read, &write); err != nil {
  1018. return nil, err
  1019. } else if err := rows.Err(); err != nil {
  1020. return nil, err
  1021. }
  1022. if _, ok := grants[userID]; !ok {
  1023. grants[userID] = make([]Grant, 0)
  1024. }
  1025. grants[userID] = append(grants[userID], Grant{
  1026. TopicPattern: fromSQLWildcard(topic),
  1027. Allow: NewPermission(read, write),
  1028. })
  1029. }
  1030. return grants, nil
  1031. }
  1032. // Grants returns all user-specific access control entries
  1033. func (a *Manager) Grants(username string) ([]Grant, error) {
  1034. rows, err := a.db.Query(selectUserAccessQuery, username)
  1035. if err != nil {
  1036. return nil, err
  1037. }
  1038. defer rows.Close()
  1039. grants := make([]Grant, 0)
  1040. for rows.Next() {
  1041. var topic string
  1042. var read, write bool
  1043. if err := rows.Scan(&topic, &read, &write); err != nil {
  1044. return nil, err
  1045. } else if err := rows.Err(); err != nil {
  1046. return nil, err
  1047. }
  1048. grants = append(grants, Grant{
  1049. TopicPattern: fromSQLWildcard(topic),
  1050. Allow: NewPermission(read, write),
  1051. })
  1052. }
  1053. return grants, nil
  1054. }
  1055. // Reservations returns all user-owned topics, and the associated everyone-access
  1056. func (a *Manager) Reservations(username string) ([]Reservation, error) {
  1057. rows, err := a.db.Query(selectUserReservationsQuery, Everyone, username)
  1058. if err != nil {
  1059. return nil, err
  1060. }
  1061. defer rows.Close()
  1062. reservations := make([]Reservation, 0)
  1063. for rows.Next() {
  1064. var topic string
  1065. var ownerRead, ownerWrite bool
  1066. var everyoneRead, everyoneWrite sql.NullBool
  1067. if err := rows.Scan(&topic, &ownerRead, &ownerWrite, &everyoneRead, &everyoneWrite); err != nil {
  1068. return nil, err
  1069. } else if err := rows.Err(); err != nil {
  1070. return nil, err
  1071. }
  1072. reservations = append(reservations, Reservation{
  1073. Topic: unescapeUnderscore(topic),
  1074. Owner: NewPermission(ownerRead, ownerWrite),
  1075. Everyone: NewPermission(everyoneRead.Bool, everyoneWrite.Bool), // false if null
  1076. })
  1077. }
  1078. return reservations, nil
  1079. }
  1080. // HasReservation returns true if the given topic access is owned by the user
  1081. func (a *Manager) HasReservation(username, topic string) (bool, error) {
  1082. rows, err := a.db.Query(selectUserHasReservationQuery, username, escapeUnderscore(topic))
  1083. if err != nil {
  1084. return false, err
  1085. }
  1086. defer rows.Close()
  1087. if !rows.Next() {
  1088. return false, errNoRows
  1089. }
  1090. var count int64
  1091. if err := rows.Scan(&count); err != nil {
  1092. return false, err
  1093. }
  1094. return count > 0, nil
  1095. }
  1096. // ReservationsCount returns the number of reservations owned by this user
  1097. func (a *Manager) ReservationsCount(username string) (int64, error) {
  1098. rows, err := a.db.Query(selectUserReservationsCountQuery, username)
  1099. if err != nil {
  1100. return 0, err
  1101. }
  1102. defer rows.Close()
  1103. if !rows.Next() {
  1104. return 0, errNoRows
  1105. }
  1106. var count int64
  1107. if err := rows.Scan(&count); err != nil {
  1108. return 0, err
  1109. }
  1110. return count, nil
  1111. }
  1112. // ReservationOwner returns user ID of the user that owns this topic, or an
  1113. // empty string if it's not owned by anyone
  1114. func (a *Manager) ReservationOwner(topic string) (string, error) {
  1115. rows, err := a.db.Query(selectUserReservationsOwnerQuery, escapeUnderscore(topic))
  1116. if err != nil {
  1117. return "", err
  1118. }
  1119. defer rows.Close()
  1120. if !rows.Next() {
  1121. return "", nil
  1122. }
  1123. var ownerUserID string
  1124. if err := rows.Scan(&ownerUserID); err != nil {
  1125. return "", err
  1126. }
  1127. return ownerUserID, nil
  1128. }
  1129. // ChangePassword changes a user's password
  1130. func (a *Manager) ChangePassword(username, password string) error {
  1131. hash, err := bcrypt.GenerateFromPassword([]byte(password), a.bcryptCost)
  1132. if err != nil {
  1133. return err
  1134. }
  1135. if _, err := a.db.Exec(updateUserPassQuery, hash, username); err != nil {
  1136. return err
  1137. }
  1138. return nil
  1139. }
  1140. // ChangeRole changes a user's role. When a role is changed from RoleUser to RoleAdmin,
  1141. // all existing access control entries (Grant) are removed, since they are no longer needed.
  1142. func (a *Manager) ChangeRole(username string, role Role) error {
  1143. if !AllowedUsername(username) || !AllowedRole(role) {
  1144. return ErrInvalidArgument
  1145. }
  1146. if _, err := a.db.Exec(updateUserRoleQuery, string(role), username); err != nil {
  1147. return err
  1148. }
  1149. if role == RoleAdmin {
  1150. if _, err := a.db.Exec(deleteUserAccessQuery, username, username); err != nil {
  1151. return err
  1152. }
  1153. }
  1154. return nil
  1155. }
  1156. // ChangeTier changes a user's tier using the tier code. This function does not delete reservations, messages,
  1157. // or attachments, even if the new tier has lower limits in this regard. That has to be done elsewhere.
  1158. func (a *Manager) ChangeTier(username, tier string) error {
  1159. if !AllowedUsername(username) {
  1160. return ErrInvalidArgument
  1161. }
  1162. t, err := a.Tier(tier)
  1163. if err != nil {
  1164. return err
  1165. } else if err := a.checkReservationsLimit(username, t.ReservationLimit); err != nil {
  1166. return err
  1167. }
  1168. if _, err := a.db.Exec(updateUserTierQuery, tier, username); err != nil {
  1169. return err
  1170. }
  1171. return nil
  1172. }
  1173. // ResetTier removes the tier from the given user
  1174. func (a *Manager) ResetTier(username string) error {
  1175. if !AllowedUsername(username) && username != Everyone && username != "" {
  1176. return ErrInvalidArgument
  1177. } else if err := a.checkReservationsLimit(username, 0); err != nil {
  1178. return err
  1179. }
  1180. _, err := a.db.Exec(deleteUserTierQuery, username)
  1181. return err
  1182. }
  1183. func (a *Manager) checkReservationsLimit(username string, reservationsLimit int64) error {
  1184. u, err := a.User(username)
  1185. if err != nil {
  1186. return err
  1187. }
  1188. if u.Tier != nil && reservationsLimit < u.Tier.ReservationLimit {
  1189. reservations, err := a.Reservations(username)
  1190. if err != nil {
  1191. return err
  1192. } else if int64(len(reservations)) > reservationsLimit {
  1193. return ErrTooManyReservations
  1194. }
  1195. }
  1196. return nil
  1197. }
  1198. // AllowReservation tests if a user may create an access control entry for the given topic.
  1199. // If there are any ACL entries that are not owned by the user, an error is returned.
  1200. func (a *Manager) AllowReservation(username string, topic string) error {
  1201. if (!AllowedUsername(username) && username != Everyone) || !AllowedTopic(topic) {
  1202. return ErrInvalidArgument
  1203. }
  1204. rows, err := a.db.Query(selectOtherAccessCountQuery, escapeUnderscore(topic), escapeUnderscore(topic), username)
  1205. if err != nil {
  1206. return err
  1207. }
  1208. defer rows.Close()
  1209. if !rows.Next() {
  1210. return errNoRows
  1211. }
  1212. var otherCount int
  1213. if err := rows.Scan(&otherCount); err != nil {
  1214. return err
  1215. }
  1216. if otherCount > 0 {
  1217. return errTopicOwnedByOthers
  1218. }
  1219. return nil
  1220. }
  1221. // AllowAccess adds or updates an entry in th access control list for a specific user. It controls
  1222. // read/write access to a topic. The parameter topicPattern may include wildcards (*). The ACL entry
  1223. // owner may either be a user (username), or the system (empty).
  1224. func (a *Manager) AllowAccess(username string, topicPattern string, permission Permission) error {
  1225. if !AllowedUsername(username) && username != Everyone {
  1226. return ErrInvalidArgument
  1227. } else if !AllowedTopicPattern(topicPattern) {
  1228. return ErrInvalidArgument
  1229. }
  1230. owner := ""
  1231. if _, err := a.db.Exec(upsertUserAccessQuery, username, toSQLWildcard(topicPattern), permission.IsRead(), permission.IsWrite(), owner, owner); err != nil {
  1232. return err
  1233. }
  1234. return nil
  1235. }
  1236. // ResetAccess removes an access control list entry for a specific username/topic, or (if topic is
  1237. // empty) for an entire user. The parameter topicPattern may include wildcards (*).
  1238. func (a *Manager) ResetAccess(username string, topicPattern string) error {
  1239. if !AllowedUsername(username) && username != Everyone && username != "" {
  1240. return ErrInvalidArgument
  1241. } else if !AllowedTopicPattern(topicPattern) && topicPattern != "" {
  1242. return ErrInvalidArgument
  1243. }
  1244. if username == "" && topicPattern == "" {
  1245. _, err := a.db.Exec(deleteAllAccessQuery, username)
  1246. return err
  1247. } else if topicPattern == "" {
  1248. _, err := a.db.Exec(deleteUserAccessQuery, username, username)
  1249. return err
  1250. }
  1251. _, err := a.db.Exec(deleteTopicAccessQuery, username, username, toSQLWildcard(topicPattern))
  1252. return err
  1253. }
  1254. // AddReservation creates two access control entries for the given topic: one with full read/write access for the
  1255. // given user, and one for Everyone with the permission passed as everyone. The user also owns the entries, and
  1256. // can modify or delete them.
  1257. func (a *Manager) AddReservation(username string, topic string, everyone Permission) error {
  1258. if !AllowedUsername(username) || username == Everyone || !AllowedTopic(topic) {
  1259. return ErrInvalidArgument
  1260. }
  1261. tx, err := a.db.Begin()
  1262. if err != nil {
  1263. return err
  1264. }
  1265. defer tx.Rollback()
  1266. if _, err := tx.Exec(upsertUserAccessQuery, username, escapeUnderscore(topic), true, true, username, username); err != nil {
  1267. return err
  1268. }
  1269. if _, err := tx.Exec(upsertUserAccessQuery, Everyone, escapeUnderscore(topic), everyone.IsRead(), everyone.IsWrite(), username, username); err != nil {
  1270. return err
  1271. }
  1272. return tx.Commit()
  1273. }
  1274. // RemoveReservations deletes the access control entries associated with the given username/topic, as
  1275. // well as all entries with Everyone/topic. This is the counterpart for AddReservation.
  1276. func (a *Manager) RemoveReservations(username string, topics ...string) error {
  1277. if !AllowedUsername(username) || username == Everyone || len(topics) == 0 {
  1278. return ErrInvalidArgument
  1279. }
  1280. for _, topic := range topics {
  1281. if !AllowedTopic(topic) {
  1282. return ErrInvalidArgument
  1283. }
  1284. }
  1285. tx, err := a.db.Begin()
  1286. if err != nil {
  1287. return err
  1288. }
  1289. defer tx.Rollback()
  1290. for _, topic := range topics {
  1291. if _, err := tx.Exec(deleteTopicAccessQuery, username, username, escapeUnderscore(topic)); err != nil {
  1292. return err
  1293. }
  1294. if _, err := tx.Exec(deleteTopicAccessQuery, Everyone, Everyone, escapeUnderscore(topic)); err != nil {
  1295. return err
  1296. }
  1297. }
  1298. return tx.Commit()
  1299. }
  1300. // DefaultAccess returns the default read/write access if no access control entry matches
  1301. func (a *Manager) DefaultAccess() Permission {
  1302. return a.defaultAccess
  1303. }
  1304. // AddTier creates a new tier in the database
  1305. func (a *Manager) AddTier(tier *Tier) error {
  1306. if tier.ID == "" {
  1307. tier.ID = util.RandomStringPrefix(tierIDPrefix, tierIDLength)
  1308. }
  1309. 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 {
  1310. return err
  1311. }
  1312. return nil
  1313. }
  1314. // UpdateTier updates a tier's properties in the database
  1315. func (a *Manager) UpdateTier(tier *Tier) error {
  1316. 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 {
  1317. return err
  1318. }
  1319. return nil
  1320. }
  1321. // RemoveTier deletes the tier with the given code
  1322. func (a *Manager) RemoveTier(code string) error {
  1323. if !AllowedTier(code) {
  1324. return ErrInvalidArgument
  1325. }
  1326. // This fails if any user has this tier
  1327. if _, err := a.db.Exec(deleteTierQuery, code); err != nil {
  1328. return err
  1329. }
  1330. return nil
  1331. }
  1332. // ChangeBilling updates a user's billing fields, namely the Stripe customer ID, and subscription information
  1333. func (a *Manager) ChangeBilling(username string, billing *Billing) error {
  1334. 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 {
  1335. return err
  1336. }
  1337. return nil
  1338. }
  1339. // Tiers returns a list of all Tier structs
  1340. func (a *Manager) Tiers() ([]*Tier, error) {
  1341. rows, err := a.db.Query(selectTiersQuery)
  1342. if err != nil {
  1343. return nil, err
  1344. }
  1345. defer rows.Close()
  1346. tiers := make([]*Tier, 0)
  1347. for {
  1348. tier, err := a.readTier(rows)
  1349. if err == ErrTierNotFound {
  1350. break
  1351. } else if err != nil {
  1352. return nil, err
  1353. }
  1354. tiers = append(tiers, tier)
  1355. }
  1356. return tiers, nil
  1357. }
  1358. // Tier returns a Tier based on the code, or ErrTierNotFound if it does not exist
  1359. func (a *Manager) Tier(code string) (*Tier, error) {
  1360. rows, err := a.db.Query(selectTierByCodeQuery, code)
  1361. if err != nil {
  1362. return nil, err
  1363. }
  1364. defer rows.Close()
  1365. return a.readTier(rows)
  1366. }
  1367. // TierByStripePrice returns a Tier based on the Stripe price ID, or ErrTierNotFound if it does not exist
  1368. func (a *Manager) TierByStripePrice(priceID string) (*Tier, error) {
  1369. rows, err := a.db.Query(selectTierByPriceIDQuery, priceID, priceID)
  1370. if err != nil {
  1371. return nil, err
  1372. }
  1373. defer rows.Close()
  1374. return a.readTier(rows)
  1375. }
  1376. func (a *Manager) readTier(rows *sql.Rows) (*Tier, error) {
  1377. var id, code, name string
  1378. var stripeMonthlyPriceID, stripeYearlyPriceID sql.NullString
  1379. var messagesLimit, messagesExpiryDuration, emailsLimit, callsLimit, reservationsLimit, attachmentFileSizeLimit, attachmentTotalSizeLimit, attachmentExpiryDuration, attachmentBandwidthLimit sql.NullInt64
  1380. if !rows.Next() {
  1381. return nil, ErrTierNotFound
  1382. }
  1383. if err := rows.Scan(&id, &code, &name, &messagesLimit, &messagesExpiryDuration, &emailsLimit, &callsLimit, &reservationsLimit, &attachmentFileSizeLimit, &attachmentTotalSizeLimit, &attachmentExpiryDuration, &attachmentBandwidthLimit, &stripeMonthlyPriceID, &stripeYearlyPriceID); err != nil {
  1384. return nil, err
  1385. } else if err := rows.Err(); err != nil {
  1386. return nil, err
  1387. }
  1388. // When changed, note readUser() as well
  1389. return &Tier{
  1390. ID: id,
  1391. Code: code,
  1392. Name: name,
  1393. MessageLimit: messagesLimit.Int64,
  1394. MessageExpiryDuration: time.Duration(messagesExpiryDuration.Int64) * time.Second,
  1395. EmailLimit: emailsLimit.Int64,
  1396. CallLimit: callsLimit.Int64,
  1397. ReservationLimit: reservationsLimit.Int64,
  1398. AttachmentFileSizeLimit: attachmentFileSizeLimit.Int64,
  1399. AttachmentTotalSizeLimit: attachmentTotalSizeLimit.Int64,
  1400. AttachmentExpiryDuration: time.Duration(attachmentExpiryDuration.Int64) * time.Second,
  1401. AttachmentBandwidthLimit: attachmentBandwidthLimit.Int64,
  1402. StripeMonthlyPriceID: stripeMonthlyPriceID.String, // May be empty
  1403. StripeYearlyPriceID: stripeYearlyPriceID.String, // May be empty
  1404. }, nil
  1405. }
  1406. // Close closes the underlying database
  1407. func (a *Manager) Close() error {
  1408. return a.db.Close()
  1409. }
  1410. // toSQLWildcard converts a wildcard string to a SQL wildcard string. It only allows '*' as wildcards,
  1411. // and escapes '_', assuming '\' as escape character.
  1412. func toSQLWildcard(s string) string {
  1413. return escapeUnderscore(strings.ReplaceAll(s, "*", "%"))
  1414. }
  1415. // fromSQLWildcard converts a SQL wildcard string to a wildcard string. It converts '%' to '*',
  1416. // and removes the '\_' escape character.
  1417. func fromSQLWildcard(s string) string {
  1418. return strings.ReplaceAll(unescapeUnderscore(s), "%", "*")
  1419. }
  1420. func escapeUnderscore(s string) string {
  1421. return strings.ReplaceAll(s, "_", "\\_")
  1422. }
  1423. func unescapeUnderscore(s string) string {
  1424. return strings.ReplaceAll(s, "\\_", "_")
  1425. }
  1426. func runStartupQueries(db *sql.DB, startupQueries string) error {
  1427. if _, err := db.Exec(startupQueries); err != nil {
  1428. return err
  1429. }
  1430. if _, err := db.Exec(builtinStartupQueries); err != nil {
  1431. return err
  1432. }
  1433. return nil
  1434. }
  1435. func setupDB(db *sql.DB) error {
  1436. // If 'schemaVersion' table does not exist, this must be a new database
  1437. rowsSV, err := db.Query(selectSchemaVersionQuery)
  1438. if err != nil {
  1439. return setupNewDB(db)
  1440. }
  1441. defer rowsSV.Close()
  1442. // If 'schemaVersion' table exists, read version and potentially upgrade
  1443. schemaVersion := 0
  1444. if !rowsSV.Next() {
  1445. return errors.New("cannot determine schema version: database file may be corrupt")
  1446. }
  1447. if err := rowsSV.Scan(&schemaVersion); err != nil {
  1448. return err
  1449. }
  1450. rowsSV.Close()
  1451. // Do migrations
  1452. if schemaVersion == currentSchemaVersion {
  1453. return nil
  1454. } else if schemaVersion > currentSchemaVersion {
  1455. return fmt.Errorf("unexpected schema version: version %d is higher than current version %d", schemaVersion, currentSchemaVersion)
  1456. }
  1457. for i := schemaVersion; i < currentSchemaVersion; i++ {
  1458. fn, ok := migrations[i]
  1459. if !ok {
  1460. return fmt.Errorf("cannot find migration step from schema version %d to %d", i, i+1)
  1461. } else if err := fn(db); err != nil {
  1462. return err
  1463. }
  1464. }
  1465. return nil
  1466. }
  1467. func setupNewDB(db *sql.DB) error {
  1468. if _, err := db.Exec(createTablesQueries); err != nil {
  1469. return err
  1470. }
  1471. if _, err := db.Exec(insertSchemaVersion, currentSchemaVersion); err != nil {
  1472. return err
  1473. }
  1474. return nil
  1475. }
  1476. func migrateFrom1(db *sql.DB) error {
  1477. log.Tag(tag).Info("Migrating user database schema: from 1 to 2")
  1478. tx, err := db.Begin()
  1479. if err != nil {
  1480. return err
  1481. }
  1482. defer tx.Rollback()
  1483. // Rename user -> user_old, and create new tables
  1484. if _, err := tx.Exec(migrate1To2CreateTablesQueries); err != nil {
  1485. return err
  1486. }
  1487. // Insert users from user_old into new user table, with ID and sync_topic
  1488. rows, err := tx.Query(migrate1To2SelectAllOldUsernamesNoTx)
  1489. if err != nil {
  1490. return err
  1491. }
  1492. defer rows.Close()
  1493. usernames := make([]string, 0)
  1494. for rows.Next() {
  1495. var username string
  1496. if err := rows.Scan(&username); err != nil {
  1497. return err
  1498. }
  1499. usernames = append(usernames, username)
  1500. }
  1501. if err := rows.Close(); err != nil {
  1502. return err
  1503. }
  1504. for _, username := range usernames {
  1505. userID := util.RandomStringPrefix(userIDPrefix, userIDLength)
  1506. syncTopic := util.RandomStringPrefix(syncTopicPrefix, syncTopicLength)
  1507. if _, err := tx.Exec(migrate1To2InsertUserNoTx, userID, syncTopic, username); err != nil {
  1508. return err
  1509. }
  1510. }
  1511. // Migrate old "access" table to "user_access" and drop "access" and "user_old"
  1512. if _, err := tx.Exec(migrate1To2InsertFromOldTablesAndDropNoTx); err != nil {
  1513. return err
  1514. }
  1515. if _, err := tx.Exec(updateSchemaVersion, 2); err != nil {
  1516. return err
  1517. }
  1518. if err := tx.Commit(); err != nil {
  1519. return err
  1520. }
  1521. return nil
  1522. }
  1523. func migrateFrom2(db *sql.DB) error {
  1524. log.Tag(tag).Info("Migrating user database schema: from 2 to 3")
  1525. tx, err := db.Begin()
  1526. if err != nil {
  1527. return err
  1528. }
  1529. defer tx.Rollback()
  1530. if _, err := tx.Exec(migrate2To3UpdateQueries); err != nil {
  1531. return err
  1532. }
  1533. if _, err := tx.Exec(updateSchemaVersion, 3); err != nil {
  1534. return err
  1535. }
  1536. return tx.Commit()
  1537. }
  1538. func migrateFrom3(db *sql.DB) error {
  1539. log.Tag(tag).Info("Migrating user database schema: from 3 to 4")
  1540. tx, err := db.Begin()
  1541. if err != nil {
  1542. return err
  1543. }
  1544. defer tx.Rollback()
  1545. if _, err := tx.Exec(migrate3To4UpdateQueries); err != nil {
  1546. return err
  1547. }
  1548. if _, err := tx.Exec(updateSchemaVersion, 4); err != nil {
  1549. return err
  1550. }
  1551. return tx.Commit()
  1552. }
  1553. func migrateFrom4(db *sql.DB) error {
  1554. log.Tag(tag).Info("Migrating user database schema: from 4 to 5")
  1555. tx, err := db.Begin()
  1556. if err != nil {
  1557. return err
  1558. }
  1559. defer tx.Rollback()
  1560. if _, err := tx.Exec(migrate4To5UpdateQueries); err != nil {
  1561. return err
  1562. }
  1563. if _, err := tx.Exec(updateSchemaVersion, 5); err != nil {
  1564. return err
  1565. }
  1566. return tx.Commit()
  1567. }
  1568. func nullString(s string) sql.NullString {
  1569. if s == "" {
  1570. return sql.NullString{}
  1571. }
  1572. return sql.NullString{String: s, Valid: true}
  1573. }
  1574. func nullInt64(v int64) sql.NullInt64 {
  1575. if v == 0 {
  1576. return sql.NullInt64{}
  1577. }
  1578. return sql.NullInt64{Int64: v, Valid: true}
  1579. }