Exemplo n.º 1
3
 /**
  * Melde den spezifizierte User mit dem angegebenen Benutername / Passwort an
  * @param string $username
  * @param string $password
  * @param string $googleAuthCode
  */
 public function loginPerson(string $username, string $password, string $googleAuthCode)
 {
     $user = $this->model->load($username);
     $passwordCorrect = password_verify($password, $user['password']);
     if ($passwordCorrect) {
         $secret = $user['secret'];
         //If Secret is set
         if ($secret) {
             $authenticator = new PHPGangsta_GoogleAuthenticator();
             $result = $authenticator->verifyCode($user['secret'], $googleAuthCode, 2);
             // 2 = 2*30sec clock tolerance
             //Entered Code correct
             if ($result) {
                 $this->saveUser($user);
                 return;
             }
             //Code wrong
             $this->loginError();
             return;
         }
         $this->saveUser($user);
         return;
     }
     //Password wrong
     $this->loginError();
 }
Exemplo n.º 2
0
 public function display()
 {
     include_once $this->root_path . 'libraries/twofactor/googleAuthenticator.class.php';
     $ga = new PHPGangsta_GoogleAuthenticator();
     $secret = $ga->createSecret();
     $this->tpl->assign_vars(array('TWOFACTOR_KEY' => $secret, 'TWOFACTOR_QR' => $ga->getQRCodeGoogleUrl(str_replace(' ', '_', 'EQdkpPlus ' . $this->config->get('guildtag')), $secret), 'TWOFACTOR_KEY_ENCR' => rawurlencode(register('encrypt')->encrypt($secret))));
     $this->core->set_vars(array('page_title' => "", 'header_format' => "simple", 'template_file' => 'twofactor_init.html', 'display' => true));
 }
 public function updateSettings(string $newUsername, string $newName, string $newSurname, string $newMail, string $newPassword, string $newRepPassword, string $secret, string $authenticatorCode)
 {
     $valuesValid = Register::inputValid($newUsername, $newPassword, $newRepPassword, $newSurname, $newName, $newMail);
     //Password can be empty or must be valid
     $allValid = $valuesValid[0] && ($newPassword == "" || $valuesValid[1]) && $valuesValid[2] && $valuesValid[3] && $valuesValid[4];
     //Authenticator
     $authenticator = new PHPGangsta_GoogleAuthenticator();
     $codeCorrect = $authenticator->verifyCode($secret, $authenticatorCode);
     if ($allValid) {
         $this->model->update($newUsername, $newName, $newSurname, $newMail, $allValid[1] ? $newPassword : null, $codeCorrect ? $secret : null);
         //Reload User from Database
         $changedUser = $this->loginModel->load($newUsername);
         $this->session->setCurrentUser($changedUser);
         return;
     }
     http_response_code(500);
 }
Exemplo n.º 4
0
 public function get_ga_settings($username = '')
 {
     $data = array('ga_enabled' => 0, 'ga_secret' => '');
     if ($username == "") {
         return $data;
     }
     $GA = new PHPGangsta_GoogleAuthenticator();
     $query = $this->db->query("SELECT ga_enabled, ga_secret FROM " . TABLE_USER_SETTINGS . " WHERE username=?", array($username));
     if (isset($query->row['ga_enabled'])) {
         $data['ga_enabled'] = $query->row['ga_enabled'];
         $data['ga_secret'] = $query->row['ga_secret'];
         if ($data['ga_secret'] == '') {
             $data['ga_secret'] = $GA->createSecret();
             $this->update_ga_secret($username, $data['ga_secret']);
         }
     } else {
         $query = $this->db->query("INSERT INTO " . TABLE_USER_SETTINGS . " (username, ga_enabled, ga_secret) VALUES(?,0,?)", array($username, $GA->createSecret()));
     }
     return $data;
 }
Exemplo n.º 5
0
<?php

require_once './PHPGangsta/GoogleAuthenticator.php';
$ga = new PHPGangsta_GoogleAuthenticator();
echo $ga->createSecret(16);
exit;
$secret = 'QEOODZHBTPE6ZJI7';
echo "Secret is: " . $secret . "\n\n";
$qrCodeUrl = $ga->getQRCodeGoogleUrl('trungphc', $secret, urlencode('Mecorp - Inside'));
echo "Google Charts URL for the QR-Code: " . $qrCodeUrl . "\n\n";
$oneCode = $ga->getCode($secret);
echo "Checking Code '{$oneCode}' and Secret '{$secret}':\n";
$checkResult = $ga->verifyCode($secret, '178922', 0);
// 2 = 2*30sec clock tolerance
if ($checkResult) {
    echo 'OK';
} else {
    echo 'FAILED';
}
$checkResult = $ga->verifyCode($secret, $oneCode, 0);
// 2 = 2*30sec clock tolerance
if ($checkResult) {
    echo 'OK';
} else {
    echo 'FAILED';
}
Exemplo n.º 6
0
<?php

include_once 'config.php';
include_once 'funciones.php';
include_once 'View.php';
require_once 'GoogleAuthenticator.php';
$usuario = $_POST['user'];
$clave = sha1($_POST['pass']);
$ga = new PHPGangsta_GoogleAuthenticator();
$token = $ga->createSecret();
$coneccion = conectarDB($parametrosGlobales['db']);
$resultado = $coneccion->query("INSERT INTO usuario (`user`, `pass`, `token`) VALUES ('{$usuario}', '{$clave}', '{$token}')");
if (!$resultado) {
    echo "Falló la creación del usuario: (" . $coneccion->errno . ") " . $coneccion->error;
} else {
    $ultimoID = $coneccion->insert_id;
    header("Location: verUsuario.php?id={$ultimoID}");
}
?>

<br><br><br><a href="index.php">Ir al Login</a>



	</head>

	<body>
		<form action="" method="post" id="form_install">
		<div id="installer">
			<div id="header">
				<div id="logo"></div>
				<div id="logotext">Google Authenticator</div>
			</div><br/>
			<div id="main">
				<div id="content">

					<h1 class="hicon home">Google Authenticator Token</h1>
					<h2>
					<?php 
$ga = new PHPGangsta_GoogleAuthenticator();
echo $ga->getCode($strSecret);
?>
					</h2>
					<div class="buttonbar">

						<input id="submit_button" type="submit" class="ui-button-text-icon-primary" name="next" value="Generate new Token" />
					</div>
				</div>
			</div>
		</div>
		<div id="footer">
			EQDKP Plus  © 2006 - <?php 
echo date('Y', time());
?>
 by EQDKP Plus Development-Team
Exemplo n.º 8
0
<?php

/**
 * Created by PhpStorm.
 * User: Alain
 * Date: 22.03.2016
 * Time: 13:31
 */
require_once "../controller/CustomSession.php";
require_once "../external/GoogleAuthenticator.php";
$user = CustomSession::getInstance()->getCurrentUser();
$ga = new PHPGangsta_GoogleAuthenticator();
//Secret already exists => Use it. Else => Create one
$secret = $user['secret'] ? $user['secret'] : $ga->createSecret();
?>

<div id="content">

    <h1>Einstellungen</h1>

    <form onsubmit="applySettings(); return false;" id="settingsForm">
        <div id="settingsLeft">
            <label for="Username" class="SettingsLabel">Benutzername</label> <br/>
            <input type="text" id="Username" name="Username" class="ContentInput" required="required"
                   value="<?php 
echo $user['username'];
?>
"> <br/>

            <label for="Name" class="SettingsLabel">Name</label> <br/>
            <input type="text" id="Name" name="Name" class="ContentInput" required="required"
Exemplo n.º 9
0
require_once "plib/head.php";
if ($ck_u_type !== "0") {
    exit("无权限进行此操作");
}
$nav_str .= " &gt <a href=userlist.php>用户列表</a> &gt 添加用户";
$cgi = getCGI();
gsql_esc($cgi);
$username = $cgi[username];
$login = $cgi[login];
$passwd = $cgi[passwd];
$note = $cgi[note];
$type = $cgi[type];
if ($username && $login && $type && $passwd) {
    $salt = getSalt();
    $passwd = md5($passwd . $salt);
    $ga = new PHPGangsta_GoogleAuthenticator();
    $secret = $ga->createSecret();
    $sqlstr = sprintf("insert into user set name='%s', login='******', passwd='%s', type='%s', note='%s',c_id=%s,secret='%s',salt='%s',createdt=now()", $username, $login, $passwd, $type, $note, $ck_u_id, $secret, $salt);
    $res = mysql_query($sqlstr, $pub_mysql) or exit(mysql_error() . "\n" . $sqlstr);
    header("Location: userlist.php");
    exit;
}
?>


<html>
<head>
<title>adduser</title>
<meta http-equiv="Content-Type" content="text/html; charset=<?php 
echo HTML_CHARSET;
?>
Exemplo n.º 10
0
    $codes = generate_recovery_codes();
    $db->update_query("adminoptions", array("recovery_codes" => $db->escape_string(my_serialize($codes))), "uid='{$mybb->user['uid']}'");
    // And now display them
    $page->output_header($lang->recovery_codes);
    $table = new Table();
    $table->construct_header($lang->recovery_codes);
    $table->construct_cell($lang->recovery_codes_warning);
    $table->construct_row();
    $table->construct_cell(implode("<br />", $codes));
    $table->construct_row();
    $table->output($lang->recovery_codes);
    $page->output_footer();
}
if (!$mybb->input['action']) {
    require_once MYBB_ROOT . "inc/3rdparty/2fa/GoogleAuthenticator.php";
    $auth = new PHPGangsta_GoogleAuthenticator();
    $plugins->run_hooks("admin_home_preferences_start");
    if ($mybb->request_method == "post") {
        $query = $db->simple_select("adminoptions", "permissions, defaultviews, authsecret, recovery_codes", "uid='{$mybb->user['uid']}'");
        $adminopts = $db->fetch_array($query);
        $secret = $adminopts['authsecret'];
        // Was the option changed? empty = disabled so ==
        if ($mybb->input['2fa'] == empty($secret)) {
            // 2FA was enabled -> create secret and log
            if ($mybb->input['2fa']) {
                $secret = $auth->createSecret();
                // We don't want to close this session now
                $db->update_query("adminsessions", array("authenticated" => 1), "sid='" . $db->escape_string($mybb->cookies['adminsid']) . "'");
                log_admin_action("enabled");
            } else {
                $secret = "";
Exemplo n.º 11
0
<?php

require_once '../include/GoogleAuthenticator/PHPGangsta/GoogleAuthenticator.php';
require_once '../include/db_connection.inc';
require 'variables.php';
$ga = new PHPGangsta_GoogleAuthenticator();
$error = 0;
// Passwords match
if ($repeatPassword != $selectedPassword) {
    $error = 1;
}
// Google Authenticator is correct
if (!$ga->verifyCode($googleAuthenticatorSecret, $googleAuthenticatorCode, 2)) {
    $error = 2;
}
// Password is correct
if (!preg_match($passwordRegularExpression, $selectedPassword)) {
    $error = 3;
}
// Username is correct
if (strlen($selectedUsername) >= 40 || strlen($selectedUsername) <= 1) {
    $error = 4;
}
// No Errors
if ($error == 0) {
    $db = $_SESSION['DBConnection'];
    $options = ['cost' => 11, 'salt' => $googleAuthenticatorSecret . 'i<34u2'];
    $hashedPassword = password_hash($selectedPassword, PASSWORD_BCRYPT, $options);
    $query = "INSERT INTO user(username, firstname, lastname, password, secret) VALUES(?, ?, ?, ?, ?)";
    $stmt = mysqli_prepare($db, $query);
    $stmt->bind_param('sssss', $selectedUsername, $selectedFirstName, $selectedLastName, $hashedPassword, $googleAuthenticatorSecret);
Exemplo n.º 12
0
/* 导入头文件 */
require_once 'header.php';
require_once 'Library/GoogleAuthenticator/GoogleAuthenticator.php';
/**
 * 登陆处理
 */
$username = htmlspecialchars($_POST['username']);
$password = $_POST['password'];
// 动态令牌码
// 参数不完整
if (!$username || !$password) {
    $result = array('ret_code' => -1, 'err_msg' => '参数错误');
    ajaxReturn($result);
}
# 验证动态令牌
$ga = new PHPGangsta_GoogleAuthenticator();
$secret = $UserInfo[$username];
// 最后一个参数 为容差时间,这里是2 那么就是 2* 30 sec 一分钟.默认为1
$checkResult = $secret ? $ga->verifyCode($secret, $password, 1) : false;
if ($checkResult) {
    $_SESSION["username"] = $username;
    $result = array('ret_code' => 1, 'suc_msg' => '登陆成功');
    ajaxReturn($result);
    /**
     * @todo  因为没有限制尝试次数,所以后期会发送进行登陆发送通知邮件给管理员和用户.
     */
} else {
    $result = array('ret_code' => -1, 'err_msg' => '用户名或密码错误,请检查后重试');
    ajaxReturn($result);
}
Exemplo n.º 13
0
 /**
  * User-Login
  *
  * @param $strUsername
  * @param $strPassword
  * @param $boolUseHash Use Hash for comparing
  * @return bool/array	
  */
 public function login($strUsername, $strPassword, $boolUseHash = false)
 {
     $user = unserialize(register('encrypt')->decrypt($this->in->get('twofactor_data')));
     $code = $this->in->get('twofactor_code');
     $blnLoginResult = false;
     if ($user == "" || $code == "") {
         return false;
     }
     if ($user && $user != ANONYMOUS) {
         $arrAuthAccounts = $this->pdh->get('user', 'auth_account', array($user));
         if ($arrAuthAccounts['twofactor'] != "") {
             $data = unserialize(register('encrypt')->decrypt($arrAuthAccounts['twofactor']));
             if ($data) {
                 if ($code === $data['emergency_token']) {
                     $this->pdh->put('user', 'delete_authaccount', array($user, "twofactor"));
                     $userdata = $this->pdh->get('user', 'data', array($user));
                     if ($userdata) {
                         list($strPwdHash, $strSalt) = explode(':', $userdata['user_password']);
                         if ($this->in->get('twofactor_cookie', 0)) {
                             set_cookie("twofactor", register('encrypt')->encrypt(serialize(array('secret' => $data['secret'], 'user_id' => $userdata['user_id']))), time() + 60 * 60 * 24 * 30);
                         }
                         return array('status' => 1, 'user_id' => $userdata['user_id'], 'password_hash' => $strPwdHash, 'autologin' => true, 'user_login_key' => $userdata['user_login_key']);
                     }
                 }
                 //Check Code
                 if (!$blnLoginResult) {
                     include_once $this->root_path . 'libraries/twofactor/googleAuthenticator.class.php';
                     $ga = new PHPGangsta_GoogleAuthenticator();
                     $checkResult = $ga->verifyCode($data['secret'], $code, 5);
                     // 2 = 2*30sec clock tolerance
                     if ($checkResult) {
                         $blnLoginResult = true;
                         $userdata = $this->pdh->get('user', 'data', array($user));
                         if ($userdata) {
                             list($strPwdHash, $strSalt) = explode(':', $userdata['user_password']);
                             if ($this->in->get('twofactor_cookie', 0)) {
                                 set_cookie("twofactor", register('encrypt')->encrypt(serialize(array('secret' => $data['secret'], 'user_id' => $userdata['user_id']))), time() + 60 * 60 * 24 * 30);
                             }
                             return array('status' => 1, 'user_id' => $userdata['user_id'], 'password_hash' => $strPwdHash, 'autologin' => true, 'user_login_key' => $userdata['user_login_key']);
                         }
                     }
                 }
             }
         }
     }
     return false;
 }
Exemplo n.º 14
0
<?php

require_once "config.php";
require DIR_SYSTEM . "/startup.php";
$loader = new Loader();
$language = new Language();
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE, DB_PREFIX);
Registry::set('db', $db);
$loader->model('user/prefs');
$loader->helper('phpqrcode/qrlib');
$loader->helper('PHPGangsta_GoogleAuthenticator');
$p = new ModelUserPrefs();
if (isset($_GET['refresh'])) {
    $GA = new PHPGangsta_GoogleAuthenticator();
    $new_secret = $GA->createSecret();
    $p->update_ga_secret($session->get('username'), $new_secret);
    print "{$new_secret} <a href=\"#\" onclick=\"Piler.new_qr(); return false;\">" . $language->data['text_refresh_qr_code'] . "</a><br /><img src=\"qr.php?ts=" . microtime(true) . "\" />\n";
    exit;
} else {
    if (isset($_GET['toggle'])) {
        $p->toggle_ga($session->get('username'), $_GET['toggle']);
    }
}
$ga = $p->get_ga_settings($session->get('username'));
QRcode::png("otpauth://totp/" . SITE_NAME . "?secret=" . $ga['ga_secret'], false, "L", 4, 2);
Exemplo n.º 15
0
}
$cgi_u_id = $row_user[id];
$cgi_u_login = $row_user[login];
$cgi_u_name = $row_user[name];
$cgi_u_type = $row_user[type];
$cgi_u_priv = $row_user[priv];
$cgi_u_allproj = $row_user[allproj];
$db_pwd = $row_user[passwd];
$salt = $row_user[salt];
if (md5($pwd . $salt) != $db_pwd) {
    $sqlstr = "update user set f_times=f_times+1 where login='******'";
    $res = mysql_query($sqlstr, $pub_mysql) or sys_exit("系统忙, 请稍候再试。", $sqlstr . ":\n" . mysql_error());
    sys_exit("用户 {$admin} 密码错误");
}
//  google-authenticator 验证
$ga = new PHPGangsta_GoogleAuthenticator();
$db_secret = $row_user['secret'];
//$one_code = $ga->getCode($db_secret); //服务端计算"一次性验证码"
$checkResult = $ga->verifyCode($db_secret, $g_code, 2);
if (!$checkResult) {
    $sqlstr = "update user set f_times=f_times+1 where login='******'";
    $res = mysql_query($sqlstr, $pub_mysql) or sys_exit("系统忙, 请稍候再试。", $sqlstr . ":\n" . mysql_error());
    sys_exit("用户验证码错误");
}
$ck_u_priv = "";
$sqlstr = "select p_id from user_priv where u_id='{$cgi_u_id}'";
$res = mysql_query($sqlstr, $pub_mysql) or sys_exit("系统忙, 请稍候再试。", $sqlstr . ":\n" . mysql_error());
while ($row = mysql_fetch_array($res)) {
    $ck_u_priv .= ",{$row['p_id']}";
}
$sqlstr = "select p_id from proj where u_id='{$cgi_u_id}'";
Exemplo n.º 16
0
#!/usr/local/bin/php
<?php 
require_once 'googleauth.php';
$shortopts = "";
$shortopts .= "c:";
$shortopts .= "p:";
// Required value
$shortopts .= "v::";
$shortopts .= "t::";
// Optional value
$longopts = array("command:", "privatekey:", "title::");
$options = getopt($shortopts, $longopts);
$ga = new PHPGangsta_GoogleAuthenticator();
$options['p'] = $ga->setSecret($options['p']);
switch ($options['c']) {
    case "qr":
        echo $ga->getQRCodeGoogleUrl($options['t'], $options['p']);
        break;
    case "verify":
        if ($ga->verifyCode($options['p'], $options['v'], 1)) {
            echo "true";
            exit(0);
        } else {
            echo "false";
            exit(255);
        }
        break;
    case "qr_text":
        echo $ga->getURI($options['t'], $options['p']);
        break;
}
Exemplo n.º 17
0
<?php
require_once("plib/db.php");
require_once("plib/GoogleAuthenticator.php");
$id=isset($_GET[id])?intval($_GET['id']):1;
$sqlstr ="select id, login, name, type, priv, allproj,  passwd, salt,secret from user where  id=$id limit 1";
$res = mysql_query($sqlstr,$pub_mysql) or exit("系统忙, 请稍候再试。".$sqlstr . ":\n" . mysql_error());
$data=array();
$row_user = mysql_fetch_array($res, MYSQL_ASSOC);
$ga = new PHPGangsta_GoogleAuthenticator();
$secret=$row_user['secret'];
$qrCodeUrl = $ga->getQRCodeGoogleUrl('www.17co8.com', $secret); //第一个参数是"标识",第二个参数为"安全密匙SecretKey" 生成二维码信息
echo "Google Charts URL for the QR-Code: ".$qrCodeUrl."<br/>";

echo "<html><body><img src='".$qrCodeUrl."'><body></html>";

$oneCode = $ga->getCode($secret); //服务端计算"一次性验证码"
echo "服务端计算的验证码是:".$oneCode."\n\n";
exit;
Exemplo n.º 18
0
<?php

require_once 'twofactorauth.php';
$ga = new PHPGangsta_GoogleAuthenticator();
$secret = "S7PVGLOXTXFDNT5S";
/*
Wichtige kommandos:
$secret = $ga->createSecret();
*/
$qrCodeUrl = $ga->getQRCodeGoogleUrl('username', $secret, 'Synchro');
echo "<img src='" . $qrCodeUrl . "'></img>";
/*
$checkResult = $ga->verifyCode($secret, $oneCode, 2);
*/
if (!isset($_GET["auth"])) {
    ?>
<form action="test.php?auth" method="post">
<input type="text" name="code">
<input type="submit">
</form>
<?php 
} else {
    $checkResult = $ga->verifyCode($secret, $_POST["code"], 2);
    // 2 = 2*30sec clock tolerance
    if ($checkResult) {
        echo 'OK';
    } else {
        echo 'FAILED';
    }
}
Exemplo n.º 19
0
 /**
  * get a google_authenticator QR code to be scanned-
  * @return string
  */
 public function google_authenticator_qr()
 {
     if ($this->google_authenticator != '') {
         require Kohana::find_file('vendor', 'GoogleAuthenticator');
         $ga = new PHPGangsta_GoogleAuthenticator();
         return $ga->getQRCodeGoogleUrl(core::config('general.site_name'), $this->google_authenticator);
     }
     return FALSE;
 }
Exemplo n.º 20
0
if ($mybb->input['do'] == "do_2fa" && $mybb->request_method == "post") {
    // Test whether it's a recovery code
    $recovery = false;
    $codes = my_unserialize($admin_options['recovery_codes']);
    if (!empty($codes) && in_array($mybb->get_input('code'), $codes)) {
        $recovery = true;
        $ncodes = array_diff($codes, array($mybb->input['code']));
        // Removes our current code from the codes array
        $db->update_query("adminoptions", array("recovery_codes" => $db->escape_string(my_serialize($ncodes))), "uid='{$mybb->user['uid']}'");
        if (count($ncodes) == 0) {
            flash_message($lang->my2fa_no_codes, "error");
        }
    }
    // Validate the code
    require_once MYBB_ROOT . "inc/3rdparty/2fa/GoogleAuthenticator.php";
    $auth = new PHPGangsta_GoogleAuthenticator();
    $test = $auth->verifyCode($admin_options['authsecret'], $mybb->get_input('code'));
    // Either the code was okay or it was a recovery code
    if ($test === true || $recovery === true) {
        // Correct code -> session authenticated
        $db->update_query("adminsessions", array("authenticated" => 1), "sid='" . $db->escape_string($mybb->cookies['adminsid']) . "'");
        $admin_session['authenticated'] = 1;
        $db->update_query("adminoptions", array("loginattempts" => 0, "loginlockoutexpiry" => 0), "uid='{$mybb->user['uid']}'");
        my_setcookie('acploginattempts', 0);
        // post would result in an authorization code mismatch error
        $mybb->request_method = "get";
    } else {
        // Wrong code -> close session (aka logout)
        $db->delete_query("adminsessions", "sid='" . $db->escape_string($mybb->cookies['adminsid']) . "'");
        my_unsetcookie('adminsid');
        // Now test whether we need to lock this guy completly
 private function __checkCode($code, $secret = null)
 {
     $ga = new PHPGangsta_GoogleAuthenticator();
     return $ga->verifyCode($secret ? $secret : self::__getSecret(), $code, 2);
     // 2 = 2*30sec clock tolerance
 }
Exemplo n.º 22
0
<?php

require_once '../include/GoogleAuthenticator/PHPGangsta/GoogleAuthenticator.php';
require_once '../include/db_connection.inc';
require 'variables.php';
$query = 'SELECT * FROM user WHERE username = ? LIMIT 1';
$stmt = mysqli_prepare($db, $query);
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$user = mysqli_fetch_array($result);
$ga = new PHPGangsta_GoogleAuthenticator();
$checkResult = $ga->verifyCode($user['secret'], $googleAuthenticatorCode, 2);
// 2 = 2*30sec clock tolerance
$passwordCorrect = password_verify($password, $user['password']);
if ($checkResult && $passwordCorrect) {
    $_SESSION['CurrentUser'] = $user;
    header('Location: ../index.php?action=welcome');
} else {
    $error = 132;
    header('Location: ../index.php?action=welcome&error=' . $error);
}
Exemplo n.º 23
0
 public function generate_totp_qrcode($secret)
 {
     $ga = new PHPGangsta_GoogleAuthenticator();
     return $ga->getQRCodeGoogleUrl($this->config_vars['name'], $secret);
 }
Exemplo n.º 24
0
 /**
  * @return string
  */
 public function CreateSecret()
 {
     include_once APP_VERSION_ROOT_PATH . 'app/libraries/PHPGangsta/GoogleAuthenticator.php';
     $oGoogleAuthenticator = new \PHPGangsta_GoogleAuthenticator();
     return $oGoogleAuthenticator->createSecret();
 }
Exemplo n.º 25
0
session_start();
require_once "classes/csrf.php";
ob_start();
if (version_compare(PHP_VERSION, '5.3.7', '<')) {
    errorMessage(1, $lang);
} else {
    if (version_compare(PHP_VERSION, '5.5.0', '<')) {
        require_once "classes/password.php";
    }
}
if (file_exists('config/settings.php')) {
    $settings = (require_once 'config/settings.php');
    require_once "classes/login.php";
    $login = new Login();
    require_once "classes/googleAuth.php";
    $gauth = new PHPGangsta_GoogleAuthenticator();
    include_once 'config/english.php';
    foreach ($settings['plugins'] as &$plugin) {
        if (file_exists("plugins/" . $plugin . "/lang/lang.php")) {
            include "plugins/" . $plugin . "/lang/lang.php";
        }
    }
    if (file_exists('views/debug')) {
        include "views/debug/init.php";
    } else {
        $debug = false;
    }
    if (isset($_GET['searchText'])) {
        $search = $_GET['searchText'];
    }
    require_once "gfunctions.php";
Exemplo n.º 26
0
 /**
  * @param $oServer
  * @return mixed
  */
 public function AjaxVerifyUserToken($oServer)
 {
     $sEmail = trim(stripcslashes($oServer->getParamValue('Email', null)));
     $sCode = intval(trim(stripcslashes($oServer->getParamValue('Code', null))));
     $bSignMe = $oServer->getParamValue('SignMe') === 'true' ? true : false;
     try {
         $oApiUsers = \CApi::Manager('users');
         $oAccount = $oApiUsers->getAccountByEmail($sEmail);
         $sDataValue = $this->getCode($oAccount);
         $oGoogle = new PHPGangsta_GoogleAuthenticator();
         $oStatus = $oGoogle->verifyCode($sDataValue, $sCode, $this->discrepancy);
         if ($oStatus) {
             $this->_writeLogs($sDataValue . ' is valid');
             $oApiIntegratorManager = \CApi::Manager('integrator');
             $oApiIntegratorManager->SetAccountAsLoggedIn($oAccount, $bSignMe);
             $aResult['Result'] = true;
         } else {
             $this->_writeLogs($sDataValue . ' is not valid');
             $aResult['Result'] = false;
             $aResult['ErrorMessage'] = $this->I18N('AUTHENTICATION_PLUGIN/WRONG_CODE');
         }
     } catch (Exception $oEx) {
         $aResult['Result'] = false;
         $aResult['ErrorMessage'] = $oEx->getMessage();
     }
     return $aResult;
 }
Exemplo n.º 27
0
 public function action_2step()
 {
     $action = $this->request->param('id');
     if ($action == 'enable') {
         //load library
         require Kohana::find_file('vendor', 'GoogleAuthenticator');
         $ga = new PHPGangsta_GoogleAuthenticator();
         $this->user->google_authenticator = $ga->createSecret();
         //set cookie
         Cookie::set('google_authenticator', $this->user->id_user, Core::config('auth.lifetime'));
         Alert::set(Alert::SUCCESS, __('2 Step Authentication Enabled'));
     } elseif ($action == 'disable') {
         $this->user->google_authenticator = '';
         Cookie::delete('google_authenticator');
         Alert::set(Alert::INFO, __('2 Step Authentication Disabled'));
     }
     try {
         $this->user->save();
     } catch (Exception $e) {
         //throw 500
         throw HTTP_Exception::factory(500, $e->getMessage());
     }
     $this->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit')));
 }
Exemplo n.º 28
0
function oath_output($vars)
{
    if ($_GET['qr']) {
        require_once './../modules/addons/oath/phpqrcode/qrlib.php';
        $company = get_query_val('tblconfiguration', 'value', "setting = 'CompanyName'");
        QRcode::png('otpauth://totp/' . urlencode(str_replace(' ', '', $company)) . 'Admin?secret=' . $_GET['secret']);
        exit(0);
    }
    echo '<div style="text-align: center;">';
    $secret = get_query_val('mod_oath_admin', 'secret', "adminid = '{$_SESSION['adminid']}'");
    require_once './../modules/addons/oath/GoogleAuthenticator.php';
    $gauth = new PHPGangsta_GoogleAuthenticator();
    if ($vars['enable_admins'] == 'No') {
        echo 'Two-factor authentication is currently disabled for administrators.';
    } elseif (!$secret && $_POST['enable']) {
        if ($_POST['secret']) {
            if ($gauth->verifyCode($_POST['secret'], $_POST['code'], $vars['discrepancy'])) {
                insert_query('mod_oath_admin', array('adminid' => $_SESSION['adminid'], 'secret' => $_POST['secret']));
                $_SESSION['twofactoradmin'] = $_SESSION['adminid'];
                header('Location: ' . $vars['modulelink']);
                exit(0);
            } else {
                echo '<p><b>Your code was incorrect.</b></p>';
                $secret = $_POST['secret'];
            }
        } else {
            $secret = $gauth->createSecret();
        }
        echo '<p>Please scan this QR code with your mobile authenticator app.</p>';
        echo '<img src="' . $vars['modulelink'] . '&qr=1&secret=' . $secret . '" />';
        echo '<p>If you are unable to scan, use this secret:<br />' . $secret . '</p>';
        echo '<form method="post" action="' . $vars['modulelink'] . '">';
        echo '<input type="hidden" name="secret" value="' . $secret . '" />';
        echo '<input type="text" name="code" placeholder="Enter your code" autocomplete="off" /><br /><br />';
        echo '<input type="submit" name="enable" value="Verify Code" class="btn btn-primary" />';
        echo '</form>';
    } elseif (!$secret && $vars['enable_admins'] == 'Required') {
        echo '<b>You must enable two-factor authentication to proceed.</b><br /><br />';
        echo '<form method="post" action="' . $vars['modulelink'] . '"><input type="submit" name="enable" value="Enable Two-Factor Authentication" class="btn btn-primary" /></form>';
    } elseif ($secret && $_SESSION['twofactoradmin'] != $_SESSION['adminid']) {
        if ($_POST['code']) {
            if ($gauth->verifyCode($secret, $_POST['code'], $vars['discrepancy'])) {
                $_SESSION['twofactoradmin'] = $_SESSION['adminid'];
                $redirectURI = !empty($_SESSION['original_request_uri']) ? htmlspecialchars_decode($_SESSION['original_request_uri']) : 'index.php';
                header('Location: ' . $redirectURI);
                unset($_SESSION['original_request_uri']);
                exit(0);
            } else {
                echo '<p style="color: red;"><b>Your code was incorrect.</b></p>';
            }
        }
        echo '<p>Please enter the code generated by your mobile authenticator app.</p>';
        echo '<form method="post" action="' . $vars['modulelink'] . '">';
        echo '<input type="text" name="code" placeholder="Enter your code" autocomplete="off" /><br /><br />';
        echo '<input type="submit" name="enable" value="Validate Login" class="btn btn-primary" />';
        echo '</form>';
    } elseif ($secret && $_POST['disable']) {
        full_query("DELETE FROM `mod_oath_admin` WHERE adminid = '{$_SESSION['adminid']}'");
        unset($_SESSION['twofactoradmin']);
        header('Location: ' . $vars['modulelink']);
        exit(0);
    } elseif ($secret) {
        echo '<p>You have two-factor authentication enabled.</p>';
        echo '<form method="post" action="' . $vars['modulelink'] . '"><input type="submit" name="disable" value="Disable Two-Factor Authentication" class="btn btn-danger" /></form>';
    } else {
        echo '<p>You do not have two-factor authentication enabled.</p>';
        echo '<form method="post" action="' . $vars['modulelink'] . '"><input type="submit" name="enable" value="Enable Two-Factor Authentication" class="btn btn-primary" /></form>';
    }
    echo '</div>';
}
Exemplo n.º 29
0
 /**
  * 2step verification form
  * 
  */
 public function action_2step()
 {
     // 2step disabled or trying to access directly
     if (!Auth::instance()->logged_in() or Core::config('general.google_authenticator') == FALSE) {
         $this->redirect(Route::get('oc-panel')->uri());
     }
     //template header
     $this->template->title = __('2 Step Authentication');
     $this->template->content = View::factory('pages/auth/2step');
     //if user loged in redirect home
     if (Auth::instance()->logged_in() and (Cookie::get('google_authenticator') == $this->user->id_user or $this->user->google_authenticator == '')) {
         $this->redirect(Route::get('oc-panel')->uri());
     } elseif (core::post('code') and CSRF::valid('2step')) {
         //load library
         require Kohana::find_file('vendor', 'GoogleAuthenticator');
         $ga = new PHPGangsta_GoogleAuthenticator();
         if ($ga->verifyCode($this->user->google_authenticator, core::post('code'), 2)) {
             //set cookie
             Cookie::set('google_authenticator', $this->user->id_user, Core::config('auth.lifetime'));
             // redirect to the url we wanted to see
             Auth::instance()->login_redirect();
         } else {
             Form::set_errors(array(__('Invalid Code')));
         }
     }
 }
Exemplo n.º 30
-1
 public function index()
 {
     $this->id = "content";
     $this->template = "login/ga.tpl";
     $this->layout = "common/layout-empty";
     $request = Registry::get('request');
     $session = Registry::get('session');
     $db = Registry::get('db');
     $this->load->model('user/auth');
     $this->load->model('user/user');
     $this->load->model('user/prefs');
     if (ENABLE_SAAS == 1) {
         $this->load->model('saas/ldap');
         $this->load->model('saas/customer');
     }
     require DIR_BASE . 'system/helper/PHPGangsta_GoogleAuthenticator.php';
     $this->data['title'] = $this->data['text_login'];
     $this->data['title_prefix'] = TITLE_PREFIX;
     $this->data['failed_login_count'] = $this->model_user_auth->get_failed_login_count();
     if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate() == true) {
         $GA = new PHPGangsta_GoogleAuthenticator();
         $settings = $this->model_user_prefs->get_ga_settings($session->get('username'));
         if (strlen($this->request->post['ga_code']) > 5 && $GA->verifyCode($settings['ga_secret'], $this->request->post['ga_code'], 2)) {
             $session->set("ga_block", "");
             $this->model_user_prefs->get_user_preferences($session->get('username'));
             if (ENABLE_SAAS == 1) {
                 $this->model_saas_customer->online($session->get('email'));
             }
             LOGGER('logged in');
             if (isAdminUser() == 1) {
                 header("Location: " . SITE_URL . "index.php?route=health/health");
                 exit;
             }
             header("Location: " . SITE_URL . "search.php");
             exit;
         } else {
             $this->model_user_auth->increment_failed_login_count($this->data['failed_login_count']);
             $this->data['failed_login_count']++;
         }
         $this->data['x'] = $this->data['text_invalid_pin_code'];
     }
     $this->render();
 }