. * * @package LibreNMS * @link http://librenms.org * @copyright 2018 Tony Murray * @author Tony Murray */ namespace App\Models; class ApiToken extends BaseModel { public $timestamps = false; protected $table = 'api_tokens'; // ---- Helper Functions ---- /** * Check if the given token is valid * * @param string $token * @return bool */ public static function isValid($token, $user_id = null) { $query = self::query()->isEnabled()->where('token_hash', $token); if (!is_null($user_id)) { $query->where('user_id', $user_id); } return $query->exists(); } /** * Get User model based on the given API token (or null if invalid) * * @param string $token * @return User|null */ public static function userFromToken($token) { return User::find(self::idFromToken($token)); } /** * Get the user_id for the given token. * * @param string $token * @return int */ public static function idFromToken($token) { return self::query()->isEnabled()->where('token_hash', $token)->value('user_id'); } // ---- Query scopes ---- public function scopeIsEnabled($query) { return $query->where('disabled', 0); } // ---- Define Relationships ---- public function user() { return $this->belongsTo('App\Models\User', 'user_id'); } }