Server Side Swift with Vapor - Part 27: Passwords | Ray Wenderlich

Isn’t this going to result in the Token table just growing without bound? I’m thinking we should implement an “upsert” type action here so that a user only ever has a single token. Would there ever be a case where it would make sense for them to have more than just the most recent one listed? Maybe something like this?

func loginHandler(_ req: Request) throws -> Future<Token> {
    let user = try req.requireAuthenticated(User.self)
    let token = try Token.generate(for: user)
    let id = try user.requireID()

    return Token.query(on: req)
        .filter(\.userID == id)
        .delete()
        .flatMap(to: Token.self) { _ in
            return token.save(on: req)
    }
}

A common use case is multiple devices - so a user can be logged in via their tablet and phone etc. A better way is to use an expiry time, and then leverage a worker to clean up the database or something like Redis to do it for you. It’s slightly out of scope for the book though

1 Like

@hercip Use this:

let random = try CryptoRandom().generateData(count: 16)

Actually, it could happen and you can do that, cause it’s not that difficult to establish a digital payment service. And you could go further and connect crypto currencies with your online purchase, like https://cryptoassetsrank.com/.