! * @brief Add an account to the database * @param[in] Username as String * @param[in] Plain text password to be hashed herein * @param[in] Access Level ranging from 0-9 * @returns Returns an enum value based upon result, 0 == SUCCESS */
| 29 | * @returns Returns an enum value based upon result, 0 == SUCCESS |
| 30 | */ |
| 31 | DBToolResult DBConnection::addAccount(const QString &username, const QString &password, uint16_t access_level) |
| 32 | { |
| 33 | qInfo().noquote() << "Adding new account to" << getName() << "database"; |
| 34 | |
| 35 | if(!m_query->prepare("INSERT INTO accounts (username,passw,access_level,salt,creation_date) VALUES (?,?,?,?,?);")) |
| 36 | { |
| 37 | qDebug() << "SQL_ERROR:" << m_query->lastError(); |
| 38 | return DBToolResult::QUERY_PREP_FAILED; |
| 39 | } |
| 40 | |
| 41 | PasswordHasher hasher; |
| 42 | QByteArray salt = hasher.generateSalt(); |
| 43 | QByteArray password_array = hasher.hashPassword(password.toUtf8(), salt); |
| 44 | QString created_date = QDateTime::currentDateTime().toString(); |
| 45 | m_query->bindValue(0, username); |
| 46 | m_query->bindValue(1, password_array); |
| 47 | m_query->bindValue(2, access_level); |
| 48 | m_query->bindValue(3, salt); |
| 49 | m_query->bindValue(4, created_date); |
| 50 | |
| 51 | if(!m_query->exec()) |
| 52 | { |
| 53 | int sqlErrorCode = m_query->lastError().nativeErrorCode().toInt(); |
| 54 | if(sqlErrorCode == 19 || sqlErrorCode == 1062 || sqlErrorCode == 23503) |
| 55 | { |
| 56 | // Unique constraint error. |
| 57 | // SQLite: 19 |
| 58 | // MySQL: 1062 |
| 59 | // PostgreSQL: 23503 |
| 60 | qWarning() << "Error: Username already taken. Please try another name."; |
| 61 | return DBToolResult::USERNAME_TAKEN; |
| 62 | } |
| 63 | qDebug() << "SQL_ERROR:" << m_query->lastError(); // Why the query failed |
| 64 | return DBToolResult::QUERY_FAILED; |
| 65 | } |
| 66 | |
| 67 | // attempt to commit transaction |
| 68 | if(!m_db->commit()) |
| 69 | { |
| 70 | qWarning() << "Commit unsuccessful, rolling back database."; |
| 71 | m_db->rollback(); |
| 72 | return DBToolResult::QUERY_FAILED; |
| 73 | } |
| 74 | |
| 75 | qInfo() << "Successfully added user" << username << "to database"; |
| 76 | return DBToolResult::SUCCESS; |
| 77 | } |
| 78 | |
| 79 | //! @} |
no test coverage detected