/
AddAdminUserCommand.swift
70 lines (56 loc) · 2.07 KB
/
AddAdminUserCommand.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//
// AddAdminUserCommand.swift
// App
//
// Created by TOMOYUKI NAKAGOMI on 2018/10/19.
//
import Vapor
import MySQL
import FluentMySQL
import Crypto
struct AddAdminUserCommand: Command {
static func addCommand(to commandConfig: inout CommandConfig) {
commandConfig.use(AddAdminUserCommand(), as: "addAdmin")
}
var arguments: [CommandArgument] {
return [
.argument(name: "name"),
.argument(name: "email"),
.argument(name: "password")
]
}
var options: [CommandOption] {
return [
]
}
var help: [String] {
return ["This command is for registering new admin user. Please enter name/email/password for new one."]
}
func run(using context: CommandContext) throws -> Future<Void> {
let name = try context.argument("name")
let email = try context.argument("email")
let password = try context.argument("password")
let hash = try BCrypt.hash(password)
let container = context.container
return container.withNewConnection(to: .mysql) {
conn in
return User.query(on: conn).filter(\User.email == email).count().flatMap() {
count in
if count > 0 {
context.console.print("[" + email + "] is already registered.")
return .done(on: context.container)
}
else {
context.console.print("------- Registered ------")
context.console.print("Name : " + name)
context.console.print("e-mail : " + email)
context.console.print("password : " + password)
context.console.print("-----------------------")
let admin = User(name: name, email: email, passwordHash: hash)
return [admin.create(on: conn)
].flatten(on: container).transform(to: ())
}
}
}
}
}