Swift后台swiftiOS学习

Swift 后台开发 -- 登录授权(User & Mo

2016-11-03  本文已影响1773人  YxxxHao

最近一周感觉特别忙,导致很多东西没有来得及总结,今天总结下如何通过 Vapor 中的 User 和 Model 来实现一个登录和授权功能。如果对 Vapor 环境搭建和添加 MySQL 数据库不太清楚的,可以看我前面写的文章

先上效果图:

8215D380-4688-4C43-8122-F843E619D52B.png

首先们先在工程目录 -> Sources -> App -> Models 目录下创建 Users.swift:

9ADAFE18-C170-47BD-813E-00505B2CA029.png

在这里需要注意的是我创建文件后,在 Xcode 里面显示的是 Users.swift ,而不是图上的 Models/Users.swift,在 Xcode 里面编译不过,但是在命令行里编译就过了,功能也正常,只有把整个工程清空,然后再 build 后,构建出来的 Xcode 工程才显示 Models/Users.swift,在 Xcode 里面才能正常编译通过,这个问题的原因不详,可能是 Xcode 的原因,也可能是其它,知道的朋友希望能告诉下我。

然后我们创建一个继承 Vapor User 的 EBUser 类(如果类名为User时,实现User protocol 时会出现问题):

final class EBUser: User {
    var id: Node?
    var username: String
    var nickname: String
    var avatar: String
    var password: String
    var exists: Bool = false

    init(node: Node, in context: Context) throws {
        
    }
    func makeNode(context: Context) throws -> Node {
        
    }
    static func prepare(_ database: Database) throws {
        
    }       
    static func revert(_ database: Database) throws {
        
    }       
}

并实现必须实现的 protocol,其中:

var id: Node?

这个属性是必须提供的,他充当的是数据库表中的主键;

var exists: Bool = false

这个属性说明的是数据表是不存在的,Vapor是建议提供的,后续版本可能会强制必须提供。

其中的 init(node: Node, in context: Context) 和 func makeNode(context: Context) throws -> Node 格式是固定的了,如下:

init(node: Node, in context: Context) throws {
    id = try node.extract("id")
    username = try node.extract("username")
    nickname = try node.extract("nickname")
    avatar = try node.extract("avatar")
    password = try node.extract("password")
}

func makeNode(context: Context) throws -> Node {
    return try Node(node: [
        "id": id,
        "username": username,
        "nickname": nickname,
        "avatar": avatar,
        "password": password
        ])
}

这里的参数名和数据表里面的字段是对应的。

这里重点说下 prepare 和 revert 两个方法,这两个方法一个是创建表的,一个是删除表的,内容格式如下:

static func prepare(_ database: Database) throws {
    try database.create("ebusers") { users in
        users.id()
        users.string("username")
        users.string("nickname")
        users.string("avatar")
        users.string("password")
    }
}

static func revert(_ database: Database) throws {
    try database.delete("ebusers")
}

这里需要注意的是,就是表名要在类名上加个s,如 ebusers,原因不详,可能是 bug, 要不使用时会报一个表名错误。prepare 在表还没有创建过的时候,执行工程就会自动执行并创建对应的表,revert 方法则需要通过配置 arguments 执行:

7CC0E09B-D8DF-42B2-AB99-7228849F834C.png

在这一部分内容中,User是和 Model 基本相同的,只是实现的协议不同罢了,而 User 中与 Model 最大不的同点就是 authenticate:

public protocol Authenticator {
    static func authenticate(credentials: Credentials) throws -> User
    static func register(credentials: Credentials) throws -> User
}
public protocol User: Entity, Account, Authenticator { }

Authenticator 协议有两个方法,一个是授权,一个是注册,然后在 EBUser 中实现这两个协议方法:

static func authenticate(credentials: Credentials) throws -> User {
    var user: EBUser?
    switch credentials {
     // 通过密码和用户名校验
    case let credentials as UsernamePassword:
        let fetchedUser = try EBUser.query()
            .filter("username", credentials.username)
            .first()
        if let password = fetchedUser?.password,
            password != "",
            (try? BCrypt.verify(password: credentials.password, matchesHash: password)) == true {
            user = fetchedUser
        }
        
     // 这里可以添加其它方式校验
        
    default:
        throw UnsupportedCredentialsError()
    }
    
    if let user = user {
        return user
    } else {
        throw IncorrectCredentialsError()
    }
}

static func register(credentials: Credentials) throws -> Auth.User {
    var user: EBUser
    switch credentials {
    case let credentials as UsernamePassword:
        user = EBUser(credentials: credentials)
    default:
        throw UnsupportedCredentialsError()
    }
    
    if try EBUser.query().filter("username", user.username).first() == nil {
        try user.save()
        return user
    } else {
        throw AccountTakenError()
    }
}

这里先不单独讲解这两个方法使用,结合 main.swift 中的接口内容来说,先看 main.swift 内容:

import Vapor
import VaporMySQL
import HTTP
import Auth
import Turnstile
import TurnstileCrypto

let drop = Droplet()
let auth = AuthMiddleware(user: EBUser.self)
drop.addConfigurable(middleware: auth, name: "auth")
let mysql = try VaporMySQL.Provider(config: drop.config)
drop.addProvider(mysql)

drop.get { request in
    let user = try? request.user()
    var dashboardView = try Node(node: [
        "authenticated": user != nil,
        "baseURL": request.baseURL
        ])
    dashboardView["account"] = try user?.makeNode()
    return try drop.view.make("index", dashboardView)
}

drop.get("login") { request in
    return try drop.view.make("login")
}

drop.post("login") { request in
    guard let username = request.data["username"]?.string,
        let password = request.data["password"]?.string else {
            return try drop.view.make("login", ["flash": "Missing username or password"])
    }
    let credentials = UsernamePassword(username: username, password: password)
    do {
        try request.auth.login(credentials)
        return Response(redirect: "/")
    } catch let e {
        return try drop.view.make("login", ["flash": "Invalid username or password"])
    }
}

drop.get("register") { request in
    return try drop.view.make("register")
}

drop.post("register") { request in
    guard let username = request.data["username"]?.string,
        let password = request.data["password"]?.string else {
            return try drop.view.make("register", ["flash": "Missing username or password"])
    }
    let credentials = UsernamePassword(username: username, password: password)
    
    do {
        try _ = EBUser.register(credentials: credentials)
        try request.auth.login(credentials)
        return Response(redirect: "/")
    } catch let e as TurnstileError {
        return try drop.view.make("register", Node(node: ["flash": e.description]))
    }
}

drop.get("logout") { request in
    request.subject.logout()
    return Response(redirect: "/")
}

为了方便使用,我们对 Request 做以下的扩展:

extension Request {
    
    var baseURL: String {
        return uri.scheme + "://" + uri.host + (uri.port == nil ? "" : ":\(uri.port!)")
    }
    
    var subject: Subject {
        return storage["subject"] as! Subject
    }
    
    func user() throws -> User {
        guard let user = try auth.user() as? EBUser else {
            throw Abort.custom(status: .badRequest, message: "Invalid user type.")
        }
        return user
    }
}

在使用 User 的 auth 功能时,我们需要把 AuthMiddleware 添加到 drop 里面:

let auth = AuthMiddleware(user: EBUser.self)
drop.preparations = [EBUser.self, Course.self]

这里添加 MySQL 的配置是时是直接从 config 里面读取:

let mysql = try VaporMySQL.Provider(config: drop.config)

使用这种方法时,我们需要在工程目录 -> Sources -> Config 目录下添加一个 mysql.json 文件,文件内容格式如下:

3924F5F0-8AA6-4F4C-9FDF-531B084217C1.png

这里也是和上篇中 MySQL 的配置的不同点。

我们看首页的请求实现方法:

drop.get { request in
    let user = try? request.user()
    var dashboardView = try Node(node: [
        "authenticated": user != nil,
        "baseURL": request.baseURL
        ])
    dashboardView["account"] = try user?.makeNode()
    return try drop.view.make("index", dashboardView)
}

我们首先会获取 request 里的 auth 的 user 对象(这里用到了上面提及的request的扩展方法user()和baseURL属性),如果在请求中没有获取的 atuh 的 user,证明用户还没有登录,我们则把一个名为 authenticated 的属性设置为 flase 传到页面, 这里的页面都使用了 leaf 语言来编写,leaf 的基本语法可以看官网介绍。

在登录功能中,这里一共写了三个页面, 首页(index.leaf)、登录页(login.leaf)、注册页(register.leaf):

378F0D2C-FC61-494C-B586-D3A1239C400F.png

index.leaf 内容:

#extend("base")
#export("body") {
  #if(authenticated) {
<h3>Hi! #(account.username)!</h3>
  }
  ##else() {
    <h3>Hi! Sign up today!</h3>
    #raw() {
      ["name": "EBer"]
      Hello, \(name)!
    }
  }
}

login.leaf 内容:

#extend("base")
#export("body") {
<h1>Login</h1>
<form action="/login" method="POST">
  <div class="form-group">
    <label for="username">Username</label>
    <input type="text" class="form-control" name="username" placeholder="Username">
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" name="password" placeholder="Password">
  </div>
  <input type="hidden" name="_csrf" value="{{csrfToken}}">
  <button type="submit" class="btn btn-primary">Login</button>
</form>

<p>Not a user of Exam Bank? <a href="/register">Register Today!</a></p>
}

register.leaf 内容:

#extend("base")
#export("body") {
<h1>Register</h1>
<form action="/register" method="POST">
  <div class="form-group">
    <label for="username">Username</label>
    <input type="text" class="form-control" name="username" placeholder="Username">
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" name="password" placeholder="Password">
  </div>
  <input type="hidden" name="_csrf" value="{{csrfToken}}">
  <button type="submit" class="btn btn-primary">Register</button>
</form>
}

base.leaf 内容:

<html>
  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link href="/styles/app.css" rel="stylesheet">
    <script type="text/javascript" charset="utf-8" src="/styles/app.js"></script>
    <title>Exam Bank</title>
  </head>
  <body>
    <div class="container">
    <div class="header clearfix">
      <nav>
        <ul class="nav nav-pills pull-right">
          #if(authenticated) {
            <li role="presentation"><a href="/logout">Logout</a></li>
          }
          ##else() {
            <li role="presentation"><a href="/login">Login</a></li>
          }
        </ul>
      </nav>
      <h3 class="text-muted"><a href="/">Exam Bank</a></h3>
    </div>
    #if(flash) {
      <div class="alert alert-danger" role="alert">
        <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
        <span class="sr-only">Error:</span>
        #(flash)
      </div>
    }
    #import("body")
    </div>
  </body>
</html>

来看注册的方法:

drop.post("register") { request in
    guard let username = request.data["username"]?.string,
        let password = request.data["password"]?.string else {
            return try drop.view.make("register", ["flash": "Missing username or password"])
    }
    let credentials = UsernamePassword(username: username, password: password)
    
    do {
        try _ = EBUser.register(credentials: credentials)
        try request.auth.login(credentials)
        return Response(redirect: "/")
    } catch let e as TurnstileError {
        return try drop.view.make("register", Node(node: ["flash": e.description]))
    }
}

post 请求中应该传username 和 password 两个参数过来,再把这两个参数转为用户名密码证书:

let credentials = UsernamePassword(username: username, password: password)

然后调用 EBUser.register(credentials: credentials) 对该证书进行注册,然后我们执行request.auth.login(credentials) 方法。

注意,在执行 login(credentials) 方法时,会触发 EBUser 里的 func authenticate(credentials: Credentials) throws -> User 方法来进行授权判断,判断证书是否已经注册了,如果没有注册则返回相关的错误信息。

再看登录请求的实现:

drop.post("login") { request in
    guard let username = request.data["username"]?.string,
        let password = request.data["password"]?.string else {
            return try drop.view.make("login", ["flash": "Missing username or password"])
    }
    let credentials = UsernamePassword(username: username, password: password)
    do {
        try request.auth.login(credentials)
        return Response(redirect: "/")
    } catch let e {
        return try drop.view.make("login", ["flash": "Invalid username or password"])
    }
}

注册请求中已经包含了登录,这里就不重复了。需要理解的就是 request.auth.login(credentials) 方法会触发 authenticate。

这里, 基本就说完了登录的全功能了,我们简单说下 Model 的功能,Model 和 User 很相似:

public protocol Model: Entity, JSONRepresentable, StringInitializable, ResponseRepresentable { }
public protocol User: Entity, Account, Authenticator { }

它们都实现了 Entity 协议, 在上面说授权相关的内容前,说的内容主要都是 Entity 协议上的东西.

这里主要说的是, Entity 协议上封装一些基本的 sql 查询方法,如:

let fetchedUser = try EBUser.query()
                .filter("username", credentials.username)
                .first()

这里就不详细说这个了,详细直接查看官网说明

本文就写到这里,因为最近比较忙,所以更新会不定期,欢迎关注~~~

最后附上 EBUser 的完整代码:

import Foundation
import Vapor
import Auth
import HTTP
import Fluent
import Turnstile
import TurnstileCrypto

enum Error: Swift.Error {
    case userNotFound
    case registerNotSupported
    case unsupportedCredentials
}

final class EBUser: User {
    var id: Node?
    var username: String
    var nickname: String
    var avatar: String
    var password: String
    var exists: Bool = false
    
    init(username: String, nickname: String, avatar: String, password: String) {
        self.username = username
        self.nickname = nickname
        self.avatar = avatar
        self.password = BCrypt.hash(password: password)
    }
    
    init(credentials: UsernamePassword) {
        self.username = credentials.username
        self.password = BCrypt.hash(password: credentials.password)
        self.nickname = ""
        self.avatar = ""
    }

    init(node: Node, in context: Context) throws {
        id = try node.extract("id")
        username = try node.extract("username")
        nickname = try node.extract("nickname")
        avatar = try node.extract("avatar")
        password = try node.extract("password")
    }
    
    func makeNode(context: Context) throws -> Node {
        return try Node(node: [
            "id": id,
            "username": username,
            "nickname": nickname,
            "avatar": avatar,
            "password": password
            ])
    }
    
    static func prepare(_ database: Database) throws {
        try database.create("ebusers") { users in
            users.id()
            users.string("username")
            users.string("nickname")
            users.string("avatar")
            users.string("password")
        }
    }
    
    static func revert(_ database: Database) throws {
        try database.delete("ebusers")
    }
    
    static func authenticate(credentials: Credentials) throws -> User {
        var user: EBUser? 
        switch credentials {
        case let credentials as UsernamePassword:
            let fetchedUser = try EBUser.query()
                .filter("username", credentials.username)
                .first()
            if let password = fetchedUser?.password,
                password != "",
                (try? BCrypt.verify(password: credentials.password, matchesHash: password)) == true {
                user = fetchedUser
            }

        default:
            throw UnsupportedCredentialsError()
        }
        
        if let user = user {
            return user
        } else {
            throw IncorrectCredentialsError()
        }
    }

    static func register(credentials: Credentials) throws -> Auth.User {
        var user: EBUser
        
        switch credentials {
        case let credentials as UsernamePassword:
            user = EBUser(credentials: credentials)
        default:
            throw UnsupportedCredentialsError()
        }
        if try EBUser.query().filter("username", user.username).first() == nil {
            try user.save()
            return user
        } else {
            throw AccountTakenError()
        }
    }  
}
上一篇下一篇

猜你喜欢

热点阅读