Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing ISS-570 #4

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 21 additions & 24 deletions Sources/PerfectLocalAuthentication/Schema/Account.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ import StORM
import PostgresStORM
import SwiftRandom
import PerfectSMTP
import PerfectCrypto

public class Account: PostgresStORM {
public var id = ""
public var username = ""
public var password = ""
public var salt = ""
public var email = ""
public var usertype: AccountType = .provisional
public var source = "local" // local, facebook, etc
Expand Down Expand Up @@ -108,11 +110,12 @@ public class Account: PostgresStORM {
}

public func makePassword(_ p1: String) {
if let digestBytes = p1.digest(.sha256),
let hexBytes = digestBytes.encode(.hex),
let hexBytesStr = String(validatingUTF8: hexBytes) {
password = hexBytesStr
}
if let random = ([UInt8](randomCount: 16)).encode(.hex),
let salt = String(validatingUTF8: random),
let shadow = p1.encrypt(.aes_128_cbc, password: p1, salt: salt) {
password = shadow
self.salt = salt
}
}

public func isUnique() throws {
Expand Down Expand Up @@ -187,25 +190,19 @@ public class Account: PostgresStORM {

// Register User
public static func login(_ u: String, _ p: String) throws -> Account {
if let digestBytes = p.digest(.sha256),
let hexBytes = digestBytes.encode(.hex),
let hexBytesStr = String(validatingUTF8: hexBytes) {

let acc = Account()
let criteria = ["username":u,"password":hexBytesStr]
do {
try acc.find(criteria)
if acc.usertype == .provisional {
throw OAuth2ServerError.loginError
}
return acc
} catch {
print(error)
throw OAuth2ServerError.loginError
}
} else {
throw OAuth2ServerError.loginError
}
let acc = Account()
let criteria = ["username":u]
do {
try acc.find(criteria)
guard let pwd = acc.password.decrypt(.aes_128_cbc, password: p, salt: acc.salt),
pwd == p, acc.usertype != .provisional else {
throw OAuth2ServerError.loginError
}
return acc
} catch {
print(error)
throw OAuth2ServerError.loginError
}
}

public static func listUsers() -> [[String: Any]] {
Expand Down