|
| 1 | +/* |
| 2 | + * Copyright (C) 2011 Emweb bvba, Kessel-Lo, Belgium. |
| 3 | + * |
| 4 | + * See the LICENSE file for terms of use. |
| 5 | + */ |
| 6 | + |
| 7 | +#if !defined(WIN32) && !defined(__QNXNTO__) |
| 8 | +#define _XOPEN_SOURCE |
| 9 | +#include <unistd.h> |
| 10 | +#endif |
| 11 | + |
1 | 12 | #include "User.h" |
2 | 13 |
|
| 14 | +#if !defined(WIN32) && !defined(__CYGWIN__) && !defined(ANDROID) |
| 15 | +#define HAVE_CRYPT |
| 16 | +#endif |
| 17 | + |
| 18 | +#ifdef HAVE_CRYPT |
| 19 | +namespace { |
| 20 | + std::string generateSalt() { |
| 21 | + /* Salt generation from glibc manual */ |
| 22 | + unsigned long seed[2]; |
| 23 | + char salt[] = "$1$........"; |
| 24 | + const char *const seedchars = |
| 25 | + "./0123456789ABCDEFGHIJKLMNOPQRST" |
| 26 | + "UVWXYZabcdefghijklmnopqrstuvwxyz"; |
| 27 | + |
| 28 | + /* Generate a (not very) random seed. */ |
| 29 | + seed[0] = time(NULL); |
| 30 | + seed[1] = getpid() ^ (seed[0] >> 14 & 0x30000); |
| 31 | + |
| 32 | + /* Turn it into printable characters from `seedchars'. */ |
| 33 | + for (int i = 0; i < 8; i++) |
| 34 | + salt[3+i] = seedchars[(seed[i/5] >> (i%5)*6) & 0x3f]; |
| 35 | + |
| 36 | + return salt; |
| 37 | + } |
| 38 | + |
| 39 | + std::string md5(const std::string& s, const std::string& salt) { |
| 40 | + return crypt(s.c_str(), salt.c_str()); |
| 41 | + } |
| 42 | +} |
| 43 | +#endif |
| 44 | + |
3 | 45 | using namespace Wt; |
4 | 46 | using namespace Wt::Dbo; |
5 | 47 |
|
6 | | -User::User(const std::string &name, const std::string &password) : |
7 | | - name(name), |
8 | | - password(password), |
9 | | - gamesPlayed(0), |
10 | | - score(0) |
| 48 | +User::User(const std::string &name, const std::string &password) |
| 49 | + : name(name), |
| 50 | + gamesPlayed(0), |
| 51 | + score(0) |
| 52 | +{ |
| 53 | + setPassword(password); |
| 54 | +} |
| 55 | + |
| 56 | + |
| 57 | +void User::setPassword(const std::string& password) |
11 | 58 | { |
| 59 | +#ifdef HAVE_CRYPT |
| 60 | + password_ = md5(password, generateSalt()); |
| 61 | +#else |
| 62 | + // This should not be used in production... |
| 63 | + password_ = password; |
| 64 | +#endif |
| 65 | +} |
12 | 66 |
|
| 67 | +bool User::authenticate(const std::string& password) const |
| 68 | +{ |
| 69 | +#ifdef HAVE_CRYPT |
| 70 | + return md5(password, password_) == password_; |
| 71 | +#else |
| 72 | + return password_ == password; |
| 73 | +#endif |
13 | 74 | } |
0 commit comments