Module login cho CI (codeigniter) framework. En

Module này được viết mục đích để sử dụng chung chức năng tạo mật khẩu, đăng nhập, xác nhận token trong ci framework. Sau đây là cách cấu hình mudule.

Trong file autoload.php config:

$autoload[‘libraries’] = array(‘database’);

Trong file config.php config:

$config[‘authenticate’] = array(

“user” => array( // Thông tin một số column map với user

“table” => “user”,

“idCol” => “id”,

“passwordCol” => “password”,

“usernameCol” => “username”

),

“token” => array( // Thông tin một số column map với token

“table” => “token”,

“tokenCol” => “token”,

“userIdCol” => “user_id”,

“datetimeCol” => “datetime”,

),

“refresh_token” => array( // Thông tin một số column map với rếh token

“table” => “refresh_token”,

“tokenCol” => “token”,

“userIdCol” => “user_id”,

“datetimeCol” => “datetime”,

),

“one_at_time” => true, //Sẽ xoá token trước đó của user

“accesstk_life_time” => 100, //Thời gian sống của access token

“refreshtk_life_time” => 20, //Thời gian sống của refresh token

“accesstk_host” => “http://localhost:8282/ci/token/check”, //url kiểm tra token

“refreshtk_host” => “http://localhost:8282/ci/token/check”, //url refresh token để nhận lại access token mới

);

Config user, token, refresh_token sẽ map với các cột và bảng trong csdl.

Đặt file Auth.php trong thư mục library

Tải library trong constructor : $this->load->library(“Auth”);

Hàm Auth::createPassword($password); tạo password.

Hàm Auth::login($username,$passowrd); kiểm tra thông tin đăng nhập. Nếu đúng trả về access token và refresh token.

Hàm Auth::accessToken($token); kiểm tra access token có hợp lệ.

Hàm Auth:: accessTokenCurl($token); gửi token tới host để kiểm tra hợp lệ.

Hàm Auth::refreshToken($token); kiểm tra access token có hợp lệ.

Hàm Auth::refreshTokenCurl($token); gửi token tới host để kiểm tra hợp lệ.

 

 

<CODE>

<?php
defined(‘BASEPATH’) OR exit(‘No direct script access allowed’);

class Auth {
private static $msgRetOk = array(
“code” => 200,
“msg” => “Success”
);
private static $msgRetFail = array(
“code” => 500,
“msg” => “Fail”
);
public static function login($username,$password){
if($username == NULL || $password == NULL || empty($username) || empty($password)){
return NULL;
}
$ci =& get_instance();
$config = $ci->config->item(“authenticate”);
$user = $ci->db->query(“SELECT * FROM `”.$config[‘user’][‘table’].”` WHERE `”.$config[‘user’][‘usernameCol’].”`=’$username'”)->result_array();
if($user != NULL){
$user = $user[0];
}else{
return self::$msgRetFail;
}
if(self::comparePassword($user[‘password’],$password) == false){
return self::$msgRetFail;
}
$token = self::createToken($user[$config[‘user’][‘idCol’]]);
if($config[‘one_at_time’] == true){
$ci->db->query(“DELETE FROM `”.$config[‘token’][‘table’].”` WHERE `”.$config[‘token’][‘userIdCol’].”`='”.$user[$config[‘user’][‘idCol’]].”‘”);
}
$ci->db->query(“INSERT INTO `”.$config[‘token’][‘table’].”`(`”.$config[‘token’][‘tokenCol’].”`,`”.$config[‘token’][‘userIdCol’].”`) VALUES (‘”.$token.”‘,'”.$user[$config[‘user’][‘idCol’]].”‘)”);

if(isset($config[‘refresh_token’]) == true && $config[‘refresh_token’] != NULL){
$refreshtk = self::createRefreshToken($user[$config[‘user’][‘idCol’]]);
$ci->db->query(“INSERT INTO `”.$config[‘refresh_token’][‘table’].”`(`”.$config[‘refresh_token’][‘tokenCol’].”`,`”.$config[‘refresh_token’][‘userIdCol’].”`) VALUES (‘”.$refreshtk.”‘,'”.$user[$config[‘user’][‘idCol’]].”‘)”);
if($ci->db->affected_rows() > 0){
self::$msgRetOk[‘refresh_token’] = $refreshtk;
}
}
if($ci->db->affected_rows() == 0){
return self::$msgRetFail;
}
self::$msgRetOk[“token”] = $token;
return self::$msgRetOk;
}

static function createPassword($password){
$salt = self::generateSalt();
$saltPW = sha1($password.$salt);
return $saltPW.$salt;
}

static function comparePassword($storedPW,$password){
$salt = substr($storedPW, count($storedPW) – 1 -25);
$saltPW = sha1($password.$salt);
if($saltPW.$salt === $storedPW)
return true;
return false;
}

static function generateSalt() {
$string = self::generateRandomString();
$shuffled_mixture = str_shuffle(Time().$string);
return $shuffled_mixture;
}

static function generateRandomString($length = 15) {
$characters = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;
$randomString = ”;
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) – 1)];
}
return $randomString;
}

public static function accessToken($token){
if($token == NULL)
return self::$msgRetFail;
$ci =& get_instance();
$config = $ci->config->item(“authenticate”);
$time = substr($token, count($token) – 1 -13);
if($time == false || is_numeric($time) == false){
return self::$msgRetFail;
}
$time = strtotime(date(“Y-m-d H:i:s”)) – (int)($time/1000);
if($time/60 > (int)$config[‘accesstk_life_time’]){
return self::$msgRetFail;
}

$token = $ci->db->query(“SELECT * FROM `”.$config[‘token’][‘table’].”` WHERE `”.$config[‘token’][‘tokenCol’].”`=’$token'”)->result_array();
if($token != NULL){
$token = $token[0];
}else{
return self::$msgRetFail;
}
return self::$msgRetOk;
}

public static function accessTokenCurl($token){
$ci =& get_instance();
$config = $ci->config->item(“authenticate”);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $config[‘accesstk_host’]);
curl_setopt($curl, CURLOPT_USERAGENT, “Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)”);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
‘access_token: ‘.$token,
));
$result = json_decode(curl_exec($curl));
curl_close ($curl);
return $result;
}

static function createToken($id){
$random = self::generateRandomString(30);
$timestamp = round(microtime(true)*1000);
return md5($random.$timestamp.$id).$timestamp;
}

public static function refreshToken($refreshToken){
if($refreshToken == NULL)
return self::$msgRetFail;
$ci =& get_instance();
$config = $ci->config->item(“authenticate”);
if(isset($config[‘refresh_token’]) == false || $config[‘refresh_token’] == NULL)
return self::$msgRetFail;
$time = substr($refreshToken, count($refreshToken) – 1 -13);
if($time == false || is_numeric($time) == false){
return self::$msgRetFail;
}
$time = strtotime(date(“Y-m-d H:i:s”)) – (int)($time/1000);
if($time/60 > (int)$config[‘refreshtk_life_time’]){
return self::$msgRetFail;
}

$refreshToken = $ci->db->query(“SELECT * FROM `”.$config[‘refresh_token’][‘table’].”` WHERE `”.$config[‘refresh_token’][‘tokenCol’].”`=’$refreshToken'”)->result_array();
if($refreshToken != NULL){
$refreshToken = $refreshToken[0];
}else{
return self::$msgRetFail;
}
$token = self::createToken($refreshToken[$config[‘refresh_token’][‘userIdCol’]]);
if($config[‘one_at_time’] == true){
$ci->db->query(“DELETE FROM `”.$config[‘token’][‘table’].”` WHERE `”.$config[‘token’][‘userIdCol’].”`='”.$refreshToken[$config[‘refresh_token’][‘userIdCol’]].”‘”);
}
$ci->db->query(“INSERT INTO `”.$config[‘token’][‘table’].”`(`”.$config[‘token’][‘tokenCol’].”`,`”.$config[‘token’][‘userIdCol’].”`) VALUES (‘”.$token.”‘,'”.$refreshToken[$config[‘refresh_token’][‘userIdCol’]].”‘)”);
if($ci->db->affected_rows() == 0){
return self::$msgRetFail;
}
self::$msgRetOk[“msg”] = $token;
return self::$msgRetOk;
}

static function createRefreshToken($id){
$random = self::generateRandomString(30);
$timestamp = round(microtime(true)*1000);
return md5($random.$timestamp.”refresh”.$id).$timestamp;
}

public static function refreshTokenCurl($token){
$ci =& get_instance();
$config = $ci->config->item(“authenticate”);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $config[‘refreshtk_host’]);
curl_setopt($curl, CURLOPT_USERAGENT, “Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)”);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
‘refresh_token: ‘.$token,
));
$result = json_decode(curl_exec($curl));
curl_close ($curl);
return $result;
}
}

</CODE>

Bài viết liên quan