Completed
Push — master ( fff4dd...0ed508 )
by Justin
04:09
created

ApiOAuth::createToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 8
c 1
b 0
f 1
dl 0
loc 17
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
/**
4
 * Copyright (c) 2018 Justin Kuenzel (jukusoft.com)
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
20
/**
21
 * Project: JuKuCMS
22
 * License: Apache 2.0 license
23
 * User: Justin
24
 * Date: 21.08.2018
25
 * Time: 13:16
26
 */
27
28
class ApiOAuth {
29
30
	protected $row = array();
31
32
	public function __construct() {
33
		//
34
	}
35
36
	/**
37
	 * load oauth token and check, if token exists
38
	 */
39
	public function load (string $token) : bool {
40
		if (Cache::contains("oauth", "token_" + $token)) {
41
			$this->row = Cache::get("oauth", "token_" + $token);
42
43
			if ($this->isExpired()) {
44
				//clear token in cache, because key has expired
45
				Cache::clear("oauth", "token_" + $token);
46
			}
47
		} else {
48
			//get token from database
49
			$this->row = Database::getInstance()->getRow("SELECT * FROM `{praefix}api_oauth` WHERE `secret_key` = :token AND `expires` > NOW(); ", array(
50
				'token' => $token
51
			));
52
53
			if (!$this->row) {
54
				//cache value
55
				Cache::put("oauth", "token_" + $token, $this->row);
56
			}
57
		}
58
59
		return $this->row !== FALSE && !$this->isExpired();
60
	}
61
62
	public function getKey () : string {
63
		return $this->row['secret_key'];
64
	}
65
66
	public function isExpired () : bool {
67
		return $this->row !== "0000-00-00 00:00:00" && strtotime($this->row['expires']) <= strtotime('now');
68
	}
69
70
	public function getUserID () : int {
71
		return (int) $this->row['userID'];
72
	}
73
74
	public function getCreatedTimestamp () : string {
75
		return $this->row['created'];
76
	}
77
78
	/**
79
	 * create an oauth token for a specific user
80
	 *
81
	 * @param $userID integer id of user
82
	 *
83
	 * @return oauth key / token
84
	 */
85
	public static function createToken (int $userID) : string {
86
		//get setting
87
		$key_length = (int) Settings::get("oauth_key_length", 255);
88
		$expires_seconds = (int) Settings::get("oauth_expire_seconds", 86400);//default value of 1 day
89
90
		//generate a random token
91
		$token = PHPUtils::randomString($key_length);
92
93
		//insert token into database
94
		Database::getInstance()->execute("INSERT INTO `{praefix}api_oauth` (
95
			'secret_key', 'userID', 'created', 'expires'
96
		) VALUES (
97
			:secret_key, :userID, CURRENT_TIMESTAMP, DATE_ADD(NOW(), INTERVAL :seconds SECOND)
98
		)", array(
99
			'secret_key' => $token,
100
			'userID' => $userID,
101
			'seconds' => $expires_seconds
102
		));
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return string. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
103
	}
104
105
	/**
106
	 * remove an oauth token for a specific user
107
	 *
108
	 * @param $token string secret key token
109
	 */
110
	public static function removeToken (string $token) {
111
		Database::getInstance()->execute("DELETE FROM `{praefix}api_oauth` WHERE `token` = :token; ", array('token' => $token));
112
113
		//clear token in cache, if exists
114
		Cache::clear("oauth", "token_" + $token);
115
	}
116
117
	/**
118
	 * remove all expired tokens from database
119
	 */
120
	public static function removeAllOutdatedTokensToken () {
121
		Database::getInstance()->execute("DELETE FROM `{praefix}api_oauth` WHERE `expires` < NOW(); ");
122
123
		//clear token cache
124
		Cache::clear("oauth");
125
	}
126
127
}
128
129
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...
130