This repository has been archived on 2024-06-26. You can view files and clone it, but cannot push or open issues or pull requests.
sakura/app/ActionCode.php

76 lines
1.7 KiB
PHP
Raw Permalink Normal View History

<?php
2016-02-03 22:22:56 +00:00
/**
* Holds the action code handling class.
* @package Sakura
*/
namespace Sakura;
/**
2016-02-02 21:04:15 +00:00
* Used to generate one-time keys for user automatic user actions e.g. account activation.
* @package Sakura
2016-02-02 21:04:15 +00:00
* @author Julian van de Groep <me@flash.moe>
*/
2015-12-09 20:21:08 +00:00
class ActionCode
{
2016-02-02 21:04:15 +00:00
/**
* Generate an Action Code.
2016-08-05 02:35:37 +00:00
* @param string $action
* @param int $user
* @return string
2016-02-02 21:04:15 +00:00
*/
2016-12-04 16:33:52 +00:00
public static function generate(string $action, int $user = 0): string
{
2016-01-09 21:57:54 +00:00
// Generate a code
$code = bin2hex(random_bytes(8));
2016-01-09 21:57:54 +00:00
// Insert it
2016-02-25 16:06:29 +00:00
DB::table('actioncodes')
2016-08-06 14:09:01 +00:00
->insert([
'code_action' => $action,
'user_id' => $user,
'action_code' => $code,
]);
2016-01-09 21:57:54 +00:00
// Return the code
return $code;
}
2016-02-02 21:04:15 +00:00
/**
* Validate an action code.
2016-08-05 02:35:37 +00:00
* @param string $action
* @param string $code
* @param int $user
* @param bool $invalidate
* @return bool
2016-02-02 21:04:15 +00:00
*/
2016-12-04 16:33:52 +00:00
public static function validate(string $action, string $code, int $user = 0, bool $invalidate = true): bool
{
2016-01-09 21:57:54 +00:00
// Fetch the code from the db
2016-02-25 16:06:29 +00:00
$get = DB::table('actioncodes')
->where('code_action', $action)
->where('action_code', $code)
->where('user_id', $user)
->count();
2016-01-09 21:57:54 +00:00
// Invalidate the code if requested
2016-02-25 16:06:29 +00:00
if ($get && $invalidate) {
2016-01-09 21:57:54 +00:00
self::invalidate($code);
}
// Return the result
2016-02-18 23:28:44 +00:00
return $get > 0;
}
2016-02-02 21:04:15 +00:00
/**
* Make a code invalid.
2016-08-05 02:35:37 +00:00
* @param string $code
2016-02-02 21:04:15 +00:00
*/
2016-12-04 16:33:52 +00:00
public static function invalidate(string $code): void
{
2016-02-25 16:06:29 +00:00
DB::table('actioncodes')
2016-03-19 15:29:47 +00:00
->where('action_code', $code)
2016-02-25 16:06:29 +00:00
->delete();
}
}