+let logjson = (await import('@ndcode/logjson')).default
+
+return async env => {
+ let globals = await env.site.get_json('/_config/globals.json')
+ let nodemailer_noreply = await env.site.get_nodemailer(
+ '/_config/nodemailer_noreply.json'
+ )
+ let post_request = await _require('/_lib/post_request.jst')
+ let session_cookie = await _require('/_lib/session_cookie.jst')
+ let Problem = await _require('/_lib/Problem.jst')
+
+ post_request(
+ // env
+ env,
+ // endpoint
+ '/api/sign_in.json',
+ // handler
+ async (email, password) => {
+ // coerce and/or validate
+ email = email.slice(0, 256).toLowerCase()
+ password = password.slice(0, 256)
+ if (email.length === 0 || password.length < 8)
+ throw new Problem(
+ 'Bad request',
+ 'Minimum length check failed',
+ 400
+ )
+
+ let transaction = await env.site.database.Transaction()
+ try {
+ // initialize env.session_key, set cookie in env.response
+ let session = await session_cookie(env, transaction)
+
+ let account = await (
+ await (
+ await transaction.get({})
+ ).get('accounts', {})
+ ).get(email)
+ if (
+ account === undefined ||
+ password !== await logjson.logjson_to_json(
+ await account.get('password')
+ )
+ )
+ throw new Problem(
+ 'Unauthorized',
+ 'Email and password combination was incorrect.'
+ 401
+ )
+
+ if (
+ !await logjson.logjson_to_json(
+ await account.get('email_verified')
+ )
+ )
+ throw new Problem(
+ 'Email not yet verified',
+ 'Please verify your email address via email link before trying to sign in.',
+ 425
+ )
+
+ session.set('signed_in_as', transaction.json_to_logjson(email))
+
+ await transaction.commit()
+ }
+ catch (error) {
+ transaction.rollback()
+ throw error
+ }
+ }
+ )
+}