Ejemplo n.º 1
1
 /**
  * Function to enable SSO (it runs before user_login() is called)
  * If a valid CHOCOLATECHIP cookie is not found, the user will be forced to the
  * master bakery login page where have to authenticate the user.
  *
  * @return logged in USER
  */
 function loginpage_hook()
 {
     global $CFG, $USER, $DB;
     global $key, $cookieDomain, $slaveURL, $masterURL, $defaultCountry;
     $key = $this->config->skey;
     $cookieDomain = $this->config->cookiedomain;
     $masterURL = $this->config->masterurl;
     $slaveURL = $this->config->slaveurl;
     $defaultCountry = $this->config->defaultcountry;
     $mdBakery['slave'] = validateCookie();
     if (!empty($mdBakery['slave'])) {
         $username = $mdBakery['slave']['name'];
         $user = authenticate_user_login($username, null);
         if ($user) {
             complete_user_login($user);
             $urltogo = $CFG->wwwroot . '/';
             $userMail = $USER->email;
             // If dummie change init url through edit user form
             $userInit = $USER->idnumber;
             // Don't check for username because of user freedom for Firstname and Lastname display
             if ($userMail != $mdBakery['slave']['mail'] || $userInit != $mdBakery['slave']['init']) {
                 $emptyString = " ";
                 // Or just "default" string
                 $user->idnumber = $mdBakery['slave']['init'];
                 $fName = ucfirst($mdBakery['slave']['name']);
                 $user->firstname = $fName;
                 $user->lastname = $emptyString;
                 $user->email = $mdBakery['slave']['mail'];
                 $user->city = $emptyString;
                 $user->country = $defaultCountry;
                 $DB->update_record('user', $user);
             }
             redirect($urltogo);
         }
     } else {
         if (isloggedin() && !isguestuser()) {
             require_logout();
         } else {
             //				$master_redirect = $masterURL . 'user/login?return_dest=' . urlencode($slaveURL . 'login/index.php');
             //				header('Location: ' . $master_redirect);
         }
     }
 }
Ejemplo n.º 2
0
 function validation($data, $files)
 {
     global $USER;
     $errors = parent::validation($data, $files);
     update_login_count();
     // ignore submitted username
     if (!($user = authenticate_user_login($USER->username, $data['password']))) {
         $errors['password'] = get_string('invalidlogin');
         return $errors;
     }
     reset_login_count();
     if ($data['newpassword1'] != $data['newpassword2']) {
         $errors['newpassword1'] = get_string('passwordsdiffer');
         $errors['newpassword2'] = get_string('passwordsdiffer');
         return $errors;
     }
     if ($data['password'] == $data['newpassword1']) {
         $errors['newpassword1'] = get_string('mustchangepassword');
         $errors['newpassword2'] = get_string('mustchangepassword');
         return $errors;
     }
     $errmsg = '';
     //prevents eclipse warnings
     if (!check_password_policy($data['newpassword1'], $errmsg)) {
         $errors['newpassword1'] = $errmsg;
         $errors['newpassword2'] = $errmsg;
         return $errors;
     }
     return $errors;
 }
Ejemplo n.º 3
0
 public function login($username, $password)
 {
     $user = authenticate_user_login($username, $password);
     if (0 < $user->id && $user->admin) {
         $_SESSION['MoodlePlugin'] = true;
         return session_id();
         //var_export($user, true);
     }
     return MOODLEWS_ERROR;
 }
Ejemplo n.º 4
0
/**
 * podcaster basic authentication 
 *
 * @author  Humboldt Universitaet zu Berlin
 *            Christoph Soergel <*****@*****.**>
 * @version 1.0
 * @package podcaster
 *
 */
function http_basic_login()
{
    global $USER;
    $realm = 'restricted';
    $userValid = false;
    if (isloggedin()) {
        return true;
    }
    $realm = 'restricted';
    if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
        $user = authenticate_user_login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
        do {
            if (!$user) {
                $realm = 'loginerror';
                break;
            }
            $USER = $user;
            // check whether the user should be changing password
            if (get_user_preferences('auth_forcepasswordchange', false)) {
                if ($passwordchangeurl != '') {
                    $realm = 'mustchangepassword';
                } else {
                    $realm = 'mustchangepassword_butnourl';
                }
                break;
            }
            // check wether user is fully setup
            if (user_not_fully_set_up($USER)) {
                $realm = 'notfullysetup';
                break;
            }
            return true;
        } while (false);
        unset($USER);
    }
    // no credentials
    header('WWW-Authenticate: Basic realm="' . get_string($realm, 'podcaster') . '"');
    header('HTTP/1.0 401 Unauthorized');
    echo get_string($realm, 'podcaster');
    exit;
}
Ejemplo n.º 5
0
 function validation($data)
 {
     global $USER;
     $errors = array();
     update_login_count();
     // ignore submitted username
     if (!($user = authenticate_user_login($USER->username, $data['password']))) {
         $errors['password'] = get_string('invalidlogin');
         return $errors;
     }
     reset_login_count();
     if ($data['newpassword1'] != $data['newpassword2']) {
         $errors['newpassword1'] = get_string('passwordsdiffer');
         $errors['newpassword2'] = get_string('passwordsdiffer');
         return $errors;
     }
     if ($data['password'] == $data['newpassword1']) {
         $errors['newpassword1'] = get_string('mustchangepassword');
         $errors['newpassword2'] = get_string('mustchangepassword');
         return $errors;
     }
     return true;
 }
 function validation($data, $files)
 {
     global $USER;
     $errors = parent::validation($data, $files);
     update_login_count();
     // ignore submitted username
     if (!($user = authenticate_user_login($USER->username, $data['password']))) {
         $errors['password'] = get_string('invalidlogin');
         return $errors;
     }
     reset_login_count();
     if ($data['newpassword1'] != $data['newpassword2']) {
         $errors['newpassword1'] = get_string('passwordsdiffer');
         $errors['newpassword2'] = get_string('passwordsdiffer');
         return $errors;
     }
     if ($data['password'] == $data['newpassword1']) {
         $errors['newpassword1'] = get_string('mustchangepassword');
         $errors['newpassword2'] = get_string('mustchangepassword');
         return $errors;
     }
     $errmsg = '';
     //prevents eclipse warnings
     if (!check_password_policy($data['newpassword1'], $errmsg)) {
         $errors['newpassword1'] = $errmsg;
         $errors['newpassword2'] = $errmsg;
         return $errors;
     }
     // Added by SMS 8/7/2011: To make sure the password does not include special
     // characters that may result in issues when synching the password with vms
     if (!isValidPassword($data['newpassword1'])) {
         $errors['newpassword1'] .= 'Your password cannot contain the following characters: " / \\ [ ] : ; | = , + * ? < > @ & !';
         $errors['newpassword2'] .= 'Your password cannot contain the following characters: " / \\ [ ] : ; | = , + * ? < > @ & !';
     }
     return $errors;
 }
Ejemplo n.º 7
0
    print_error('shib_not_set_up_error', 'auth_shibboleth');
}
/// If we can find the Shibboleth attribute, save it in session and return to main login page
if (!empty($_SERVER[$pluginconfig->user_attribute])) {
    // Shibboleth auto-login
    $frm = new stdClass();
    $frm->username = strtolower($_SERVER[$pluginconfig->user_attribute]);
    // The password is never actually used, but needs to be passed to the functions 'user_login' and
    // 'authenticate_user_login'. Shibboleth returns true for the function 'prevent_local_password', which is
    // used when setting the password in 'update_internal_user_password'. When 'prevent_local_password'
    // returns true, the password is set to 'not cached' (AUTH_PASSWORD_NOT_CACHED) in the Moodle DB. However,
    // rather than setting the password to a hard-coded value, we will generate one each time, in case there are
    // changes to the Shibboleth plugin and it is actually used.
    $frm->password = generate_password(8);
    /// Check if the user has actually submitted login data to us
    if ($shibbolethauth->user_login($frm->username, $frm->password) && ($user = authenticate_user_login($frm->username, $frm->password))) {
        complete_user_login($user);
        if (user_not_fully_set_up($USER)) {
            $urltogo = $CFG->wwwroot . '/user/edit.php?id=' . $USER->id . '&amp;course=' . SITEID;
            // We don't delete $SESSION->wantsurl yet, so we get there later
        } else {
            if (isset($SESSION->wantsurl) and strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) {
                $urltogo = $SESSION->wantsurl;
                /// Because it's an address in this site
                unset($SESSION->wantsurl);
            } else {
                $urltogo = $CFG->wwwroot . '/';
                /// Go to the standard home page
                unset($SESSION->wantsurl);
                /// Just in case
            }
Ejemplo n.º 8
0
function teosso_authenticate_user()
{
    global $CFG, $USER, $SESSION;
    $pluginconfig = get_config('auth/teosso');
    // retrieve the login data from the HTTP Headers
    $attributes = auth_plugin_teosso::get_sso_attributes();
    // check to see if we got any authentication data
    if (empty($attributes)) {
        redirect($pluginconfig->signin_url);
    }
    // get the http headers for error reporting
    $headers = apache_request_headers();
    $attr_hdrs = array();
    foreach ($headers as $key => $value) {
        if (preg_match('/^HTTP_/', $key)) {
            $attr_hdrs[] = $key . ': ' . $value;
        }
    }
    $headers = implode(' | ', $attr_hdrs);
    // FIND THE VALIDIDTY OF THE HTTP HEADER
    $attrmap = auth_plugin_teosso::get_attributes();
    if (empty($attrmap['idnumber'])) {
        // serious misdemeanour
        print_error('missingidnumber', 'auth_teosso');
    }
    if (empty($attributes[$attrmap['idnumber']])) {
        #
        // not valid session. Ship user off to Federation Manager
        add_to_log(0, 'login', 'error', '/auth/teosso/index.php', get_string('idnumber_error', 'auth_teosso', $headers));
        redirect($pluginconfig->signin_error_url);
    } else {
        // in theory we only need acct_id at this point - we should retrieve the user record to get the username via idnumber
        if (!($user = get_record('user', 'idnumber', $attributes[$attrmap['idnumber']]))) {
            // must be a new user
            if (!empty($attributes[$attrmap['username']])) {
                $attributes['username'] = $attributes[$attrmap['username']];
            } else {
                add_to_log(0, 'login', 'error', '/auth/teosso/index.php', get_string('username_error', 'auth_teosso', $headers));
                redirect($pluginconfig->signin_error_url);
            }
        } else {
            // user must use the auth type teosso or authenticate_user_login() will fail
            if ($user->auth != 'teosso') {
                add_to_log(0, 'login', 'error', '/auth/teosso/index.php', get_string('user_auth_type_error', 'auth_teosso', $headers));
                redirect($pluginconfig->signin_error_url);
            }
            // because we want to retain acct_id as the master ID
            // we need to modify idnumber on mdl_user NOW - so it all lines up later
            if (isset($attributes[$attrmap['username']]) && $user->username != $attributes[$attrmap['username']]) {
                if (!set_field('user', 'username', $attributes[$attrmap['username']], 'id', $user->id)) {
                    print_error('usernameupdatefailed', 'auth_teosso');
                }
                $attributes['username'] = $attributes[$attrmap['username']];
            } else {
                $attributes['username'] = $user->username;
            }
        }
        // Valid session. Register or update user in Moodle, log him on, and redirect to Moodle front
        // we require the plugin to know that we are now doing a teosso login in hook puser_login
        $GLOBALS['teosso_login'] = TRUE;
        // make variables accessible to teosso->get_userinfo. Information will be requested from authenticate_user_login -> create_user_record / update_user_record
        $GLOBALS['teosso_login_attributes'] = $attributes;
        // just passes time as a password. User will never log in directly to moodle with this password anyway or so we hope?
        $USER = authenticate_user_login($attributes['username'], time());
        $USER->loggedin = true;
        $USER->site = $CFG->wwwroot;
        update_user_login_times();
        if ($pluginconfig->notshowusername) {
            // Don't show username on login page
            set_moodle_cookie('nobody');
        }
        set_login_session_preferences();
        add_to_log(SITEID, 'user', 'login', "view.php?id={$USER->id}&course=" . SITEID, $USER->id, 0, $USER->id);
        check_enrolment_plugins($USER);
        load_all_capabilities();
        // just fast copied this from some other module - might not work...
        if (isset($SESSION->wantsurl) and strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) {
            $urltogo = $SESSION->wantsurl;
        } else {
            $urltogo = $CFG->wwwroot . '/';
        }
        unset($SESSION->wantsurl);
        redirect($urltogo);
    }
}
Ejemplo n.º 9
0
 /**
  * Authentication hook - is called every time user hit the login page
  * The code is run only if the param code is mentionned.
  */
 function loginpage_hook()
 {
     global $USER, $SESSION, $CFG, $DB;
     //check the Google authorization code
     $authorizationcode = optional_param('code', '', PARAM_TEXT);
     if (!empty($authorizationcode)) {
         $authprovider = required_param('authprovider', PARAM_ALPHANUMEXT);
         //set the params specific to the authentication provider
         $params = array();
         switch ($authprovider) {
             case 'google':
                 $params['client_id'] = get_config('auth/googleoauth2', 'googleclientid');
                 $params['client_secret'] = get_config('auth/googleoauth2', 'googleclientsecret');
                 $requestaccesstokenurl = 'https://accounts.google.com/o/oauth2/token';
                 $params['grant_type'] = 'authorization_code';
                 $params['redirect_uri'] = $CFG->wwwroot . '/auth/googleoauth2/google_redirect.php';
                 $params['code'] = $authorizationcode;
                 break;
             case 'facebook':
                 $params['client_id'] = get_config('auth/googleoauth2', 'facebookclientid');
                 $params['client_secret'] = get_config('auth/googleoauth2', 'facebookclientsecret');
                 $requestaccesstokenurl = 'https://graph.facebook.com/oauth/access_token';
                 $params['redirect_uri'] = $CFG->wwwroot . '/auth/googleoauth2/facebook_redirect.php';
                 $params['code'] = $authorizationcode;
                 break;
             case 'messenger':
                 $params['client_id'] = get_config('auth/googleoauth2', 'messengerclientid');
                 $params['client_secret'] = get_config('auth/googleoauth2', 'messengerclientsecret');
                 $requestaccesstokenurl = 'https://oauth.live.com/token';
                 $params['redirect_uri'] = $CFG->wwwroot . '/auth/googleoauth2/messenger_redirect.php';
                 $params['code'] = $authorizationcode;
                 $params['grant_type'] = 'authorization_code';
                 break;
             default:
                 throw new moodle_exception('unknown_oauth2_provider');
                 break;
         }
         //request by curl an access token and refresh token
         require_once $CFG->libdir . '/filelib.php';
         if ($authprovider == 'messenger') {
             //Windows Live returns an "Object moved" error with curl->post() encoding
             $curl = new curl();
             $postreturnvalues = $curl->get('https://oauth.live.com/token?client_id=' . urlencode($params['client_id']) . '&redirect_uri=' . urlencode($params['redirect_uri']) . '&client_secret=' . urlencode($params['client_secret']) . '&code=' . urlencode($params['code']) . '&grant_type=authorization_code');
         } else {
             $curl = new curl();
             $postreturnvalues = $curl->post($requestaccesstokenurl, $params);
         }
         switch ($authprovider) {
             case 'google':
                 $postreturnvalues = json_decode($postreturnvalues);
                 $accesstoken = $postreturnvalues->access_token;
                 //$refreshtoken = $postreturnvalues->refresh_token;
                 //$expiresin = $postreturnvalues->expires_in;
                 //$tokentype = $postreturnvalues->token_type;
                 break;
             case 'facebook':
                 parse_str($postreturnvalues, $returnvalues);
                 $accesstoken = $returnvalues['access_token'];
                 break;
             case 'messenger':
                 $accesstoken = json_decode($postreturnvalues)->access_token;
                 break;
             default:
                 break;
         }
         //with access token request by curl the email address
         if (!empty($accesstoken)) {
             //get the username matching the email
             switch ($authprovider) {
                 case 'google':
                     $params = array();
                     $params['access_token'] = $accesstoken;
                     $params['alt'] = 'json';
                     $postreturnvalues = $curl->get('https://www.googleapis.com/userinfo/email', $params);
                     $postreturnvalues = json_decode($postreturnvalues);
                     $useremail = $postreturnvalues->data->email;
                     $verified = $postreturnvalues->data->isVerified;
                     break;
                 case 'facebook':
                     $params = array();
                     $params['access_token'] = $accesstoken;
                     $postreturnvalues = $curl->get('https://graph.facebook.com/me', $params);
                     $facebookuser = json_decode($postreturnvalues);
                     $useremail = $facebookuser->email;
                     $verified = $facebookuser->verified;
                     break;
                 case 'messenger':
                     $params = array();
                     $params['access_token'] = $accesstoken;
                     $postreturnvalues = $curl->get('https://apis.live.net/v5.0/me', $params);
                     $messengeruser = json_decode($postreturnvalues);
                     $useremail = $messengeruser->emails->preferred;
                     $verified = 1;
                     //not super good but there are no way to check it yet:
                     //http://social.msdn.microsoft.com/Forums/en-US/messengerconnect/thread/515d546d-1155-4775-95d8-89dadc5ee929
                     break;
                 default:
                     break;
             }
             //throw an error if the email address is not verified
             if (!$verified) {
                 throw new moodle_exception('emailaddressmustbeverified', 'auth_googleoauth2');
             }
             //if email not existing in user database then create a new username (userX).
             if (empty($useremail) or $useremail != clean_param($useremail, PARAM_EMAIL)) {
                 throw new moodle_exception('couldnotgetuseremail');
                 //TODO: display a link for people to retry
             }
             //get the user - don't bother with auth = googleoauth2 because
             //authenticate_user_login() will fail it if it's not 'googleoauth2'
             $user = $DB->get_record('user', array('email' => $useremail, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id));
             //create the user if it doesn't exist
             if (empty($user)) {
                 //get following incremented username
                 $lastusernumber = get_config('auth/googleoauth2', 'lastusernumber');
                 $lastusernumber = empty($lastusernumber) ? 1 : $lastusernumber++;
                 //check the user doesn't exist
                 $nextuser = $DB->get_record('user', array('username' => get_config('auth/googleoauth2', 'googleuserprefix') . $lastusernumber));
                 while (!empty($nextuser)) {
                     $lastusernumber = $lastusernumber + 1;
                     $nextuser = $DB->get_record('user', array('username' => get_config('auth/googleoauth2', 'googleuserprefix') . $lastusernumber));
                 }
                 set_config('lastusernumber', $lastusernumber, 'auth/googleoauth2');
                 $username = get_config('auth/googleoauth2', 'googleuserprefix') . $lastusernumber;
                 //retrieve more information from the provider
                 $newuser = new stdClass();
                 $newuser->email = $useremail;
                 switch ($authprovider) {
                     case 'google':
                         $params = array();
                         $params['access_token'] = $accesstoken;
                         $params['alt'] = 'json';
                         $userinfo = $curl->get('https://www.googleapis.com/oauth2/v1/userinfo', $params);
                         $userinfo = json_decode($userinfo);
                         //email, id, name, verified_email, given_name, family_name, link, gender, locale
                         $newuser->auth = 'googleoauth2';
                         if (!empty($userinfo->given_name)) {
                             $newuser->firstname = $userinfo->given_name;
                         }
                         if (!empty($userinfo->family_name)) {
                             $newuser->lastname = $userinfo->family_name;
                         }
                         if (!empty($userinfo->locale)) {
                             //$newuser->lang = $userinfo->locale;
                             //TODO: convert the locale into correct Moodle language code
                         }
                         break;
                     case 'facebook':
                         $newuser->firstname = $facebookuser->first_name;
                         $newuser->lastname = $facebookuser->last_name;
                         break;
                     case 'messenger':
                         $newuser->firstname = $messengeruser->first_name;
                         $newuser->lastname = $messengeruser->last_name;
                         break;
                     default:
                         break;
                 }
                 //retrieve country and city if the provider failed to give it
                 if (!isset($newuser->country) or !isset($newuser->city)) {
                     $googleipinfodbkey = get_config('auth/googleoauth2', 'googleipinfodbkey');
                     if (!empty($googleipinfodbkey)) {
                         $locationdata = $curl->get('http://api.ipinfodb.com/v3/ip-city/?key=' . $googleipinfodbkey . '&ip=' . getremoteaddr() . '&format=json');
                         $locationdata = json_decode($locationdata);
                     }
                     if (!empty($locationdata)) {
                         //TODO: check that countryCode does match the Moodle country code
                         $newuser->country = isset($newuser->country) ? isset($newuser->country) : $locationdata->countryCode;
                         $newuser->city = isset($newuser->city) ? isset($newuser->city) : $locationdata->cityName;
                     }
                 }
             } else {
                 $username = $user->username;
             }
             //authenticate the user
             //TODO: delete this log later
             $userid = empty($user) ? 'new user' : $user->id;
             add_to_log(SITEID, 'auth_googleoauth2', '', '', $username . '/' . $useremail . '/' . $userid);
             $user = authenticate_user_login($username, null);
             if ($user) {
                 //set a cookie to remember what auth provider was selected
                 setcookie('MOODLEGOOGLEOAUTH2_' . $CFG->sessioncookie, $authprovider, time() + DAYSECS * 60, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
                 //prefill more user information if new user
                 if (!empty($newuser)) {
                     $newuser->id = $user->id;
                     $DB->update_record('user', $newuser);
                 }
                 complete_user_login($user);
                 // Redirection
                 if (user_not_fully_set_up($USER)) {
                     $urltogo = $CFG->wwwroot . '/user/edit.php';
                     // We don't delete $SESSION->wantsurl yet, so we get there later
                 } else {
                     if (isset($SESSION->wantsurl) and strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) {
                         $urltogo = $SESSION->wantsurl;
                         // Because it's an address in this site
                         unset($SESSION->wantsurl);
                     } else {
                         // No wantsurl stored or external - go to homepage
                         $urltogo = $CFG->wwwroot . '/';
                         unset($SESSION->wantsurl);
                     }
                 }
                 redirect($urltogo);
             }
         } else {
             throw new moodle_exception('couldnotgetgoogleaccesstoken', 'auth_googleoauth2');
         }
     }
 }
Ejemplo n.º 10
0
                }
            }
            $new_section["modules"] = array_for_modules($section_modules);
            $sections_array[] = $new_section;
        }
    }
    $json_output["site_sections"] = $sections_array;
    if ($CFG->rolesactive) {
        $json_output["site_admin"] = has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM));
    } else {
        $json_output["site_admin"] = isadmin();
    }
    $json_output["auto_login_guests"] = $CFG->autologinguests == 1;
}
if (isset($_GET['check_user']) || $update_all && isset($_POST['username']) && isset($_POST['password'])) {
    $json_output["login_valid"] = authenticate_user_login($_POST['username'], $_POST['password']) != FALSE;
}
if (isset($_GET['course_categories']) || $update_all) {
    include_once $CFG->dirroot . '/course/lib.php';
    $categories = array();
    $given_categories = get_categories();
    foreach ($given_categories as $i => $each_category) {
        $is_admin = FALSE;
        if ($CFG->rolesactive) {
        } else {
            $is_admin = isadmin();
        }
        $show_category = $each_category->visible or $is_admin;
        if ($each_category->visible) {
            $new_category = array();
            $new_category["id"] = $each_category->id;
Ejemplo n.º 11
0
     $authorize_error = get_string("auth_saml_not_authorize", "auth_saml", $username);
     $authorize_user = false;
 }
 if (function_exists('saml_hook_authorize_user')) {
     $result = saml_hook_authorize_user($username, $saml_attributes, $authorize_user);
     if ($result !== true) {
         $authorize_user = false;
         $authorize_error = $result;
     }
 }
 if (!$authorize_user) {
     $err['login'] = "******" . $authorize_error . "</p>";
     saml_error($err, '?logout', $pluginconfig->samllogfile);
 }
 // Just passes time as a password. User will never log in directly to moodle with this password anyway or so we hope?
 $user = authenticate_user_login($username, time());
 if ($user === false) {
     $err['login'] = get_string("auth_saml_error_authentication_process", "auth_saml", $username);
     saml_error($err['login'], '?logout', $pluginconfig->samllogfile);
 }
 // Complete the user login sequence
 $user = get_complete_user_data('id', $user->id);
 if ($user === false) {
     $err['login'] = get_string("auth_saml_error_complete_user_data", "auth_saml", $username);
     saml_error($err['login'], '?logout', $pluginconfig->samllogfile);
 }
 $USER = complete_user_login($user);
 if (function_exists('saml_hook_post_user_created')) {
     saml_hook_post_user_created($USER);
 }
 if (isset($SESSION->wantsurl) && !empty($SESSION->wantsurl)) {
Ejemplo n.º 12
0
 public function test_authenticate_user_login()
 {
     global $CFG;
     $this->resetAfterTest();
     $oldlog = ini_get('error_log');
     ini_set('error_log', "{$CFG->dataroot}/testlog.log");
     // Prevent standard logging.
     set_config('lockoutthreshold', 0);
     set_config('lockoutwindow', 60 * 20);
     set_config('lockoutduration', 60 * 30);
     $_SERVER['HTTP_USER_AGENT'] = 'no browser';
     // Hack around missing user agent in CLI scripts.
     $user1 = $this->getDataGenerator()->create_user(array('username' => 'username1', 'password' => 'password1'));
     $user2 = $this->getDataGenerator()->create_user(array('username' => 'username2', 'password' => 'password2', 'suspended' => 1));
     $user3 = $this->getDataGenerator()->create_user(array('username' => 'username3', 'password' => 'password3', 'auth' => 'nologin'));
     $result = authenticate_user_login('username1', 'password1');
     $this->assertInstanceOf('stdClass', $result);
     $this->assertEquals($user1->id, $result->id);
     $reason = null;
     $result = authenticate_user_login('username1', 'password1', false, $reason);
     $this->assertInstanceOf('stdClass', $result);
     $this->assertEquals(AUTH_LOGIN_OK, $reason);
     $reason = null;
     $result = authenticate_user_login('username1', 'nopass', false, $reason);
     $this->assertFalse($result);
     $this->assertEquals(AUTH_LOGIN_FAILED, $reason);
     $reason = null;
     $result = authenticate_user_login('username2', 'password2', false, $reason);
     $this->assertFalse($result);
     $this->assertEquals(AUTH_LOGIN_SUSPENDED, $reason);
     $reason = null;
     $result = authenticate_user_login('username3', 'password3', false, $reason);
     $this->assertFalse($result);
     $this->assertEquals(AUTH_LOGIN_SUSPENDED, $reason);
     $reason = null;
     $result = authenticate_user_login('username4', 'password3', false, $reason);
     $this->assertFalse($result);
     $this->assertEquals(AUTH_LOGIN_NOUSER, $reason);
     set_config('lockoutthreshold', 3);
     $reason = null;
     $result = authenticate_user_login('username1', 'nopass', false, $reason);
     $this->assertFalse($result);
     $this->assertEquals(AUTH_LOGIN_FAILED, $reason);
     $result = authenticate_user_login('username1', 'nopass', false, $reason);
     $this->assertFalse($result);
     $this->assertEquals(AUTH_LOGIN_FAILED, $reason);
     ob_start();
     // Prevent nomailever notice.
     $result = authenticate_user_login('username1', 'nopass', false, $reason);
     ob_end_clean();
     $this->assertFalse($result);
     $this->assertEquals(AUTH_LOGIN_FAILED, $reason);
     $result = authenticate_user_login('username1', 'password1', false, $reason);
     $this->assertFalse($result);
     $this->assertEquals(AUTH_LOGIN_LOCKOUT, $reason);
     $result = authenticate_user_login('username1', 'password1', true, $reason);
     $this->assertInstanceOf('stdClass', $result);
     $this->assertEquals(AUTH_LOGIN_OK, $reason);
     ini_set('error_log', $oldlog);
 }
Ejemplo n.º 13
0
 /**
  * Sign up a new user ready for confirmation.
  * Password is passed in plaintext.
  *
  * @param object $user new user object
  * @param boolean $notify print notice with link and terminate
  */
 function user_signup($user, $notify = true)
 {
     global $CFG, $DB, $SESSION;
     require_once $CFG->dirroot . '/user/profile/lib.php';
     require_once $CFG->dirroot . '/user/lib.php';
     if (isset($SESSION->wantsurl)) {
         $wantsurl = $SESSION->wantsurl;
     }
     $plainpassword = $user->password;
     $user->password = hash_internal_user_password($user->password);
     if (empty($user->calendartype)) {
         $user->calendartype = $CFG->calendartype;
     }
     $user->confirmed = 1;
     $user->id = user_create_user($user, false, false);
     user_add_password_history($user->id, $plainpassword);
     // Save any custom profile field information.
     profile_save_data($user);
     // Trigger event.
     \core\event\user_created::create_from_userid($user->id)->trigger();
     $thisuser = authenticate_user_login($user->username, $plainpassword, false, $errorcode);
     if ($thisuser == false) {
         print_error('authfailure');
     } else {
         complete_user_login($thisuser);
         if (isset($wantsurl)) {
             $urltogo = $wantsurl;
             if (isset($_SESSION["fiaction"]) && isset($_SESSION["ficourseid"]) && is_numeric($_SESSION["ficourseid"]) && $_SESSION["fiaction"] == "enroll") {
                 $urltogo = $CFG->wwwroot . '/course/enrol.php?id=' . $_SESSION["ficourseid"];
                 unset($_SESSION['fiaction']);
                 unset($_SESSION['ficourseid']);
                 unset($SESSION->wantsurl);
             }
         } else {
             $urltogo = $CFG->wwwroot . '/';
         }
         redirect($urltogo);
     }
     // if ($notify) {
     //     global $CFG, $PAGE, $OUTPUT;
     //     $emailconfirm = get_string('emailconfirm');
     //     $PAGE->navbar->add($emailconfirm);
     //     $PAGE->set_title($emailconfirm);
     //     $PAGE->set_heading($PAGE->course->fullname);
     //     echo $OUTPUT->header();
     //     notice(get_string('emailconfirmsent', '', $user->email), "$CFG->wwwroot/index.php");
     // } else {
     //     return true;
     // }
 }
 public function __authenticate($username, $password, $serviceshortname)
 {
     global $CFG, $DB;
     //echo $OUTPUT->header();
     if (!$CFG->enablewebservices) {
         throw new moodle_exception('enablewsdescription', 'webservice');
     }
     $username = trim(textlib::strtolower($username));
     if (is_restored_user($username)) {
         throw new moodle_exception('restoredaccountresetpassword', 'webservice');
     }
     $user = authenticate_user_login($username, $password);
     if (!empty($user)) {
         //Non admin can not authenticate if maintenance mode
         $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
         if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
             throw new moodle_exception('sitemaintenance', 'admin');
         }
         if (isguestuser($user)) {
             throw new moodle_exception('noguest');
         }
         if (empty($user->confirmed)) {
             throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
         }
         // check credential expiry
         $userauth = get_auth_plugin($user->auth);
         if (!empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
             $days2expire = $userauth->password_expire($user->username);
             if (intval($days2expire) < 0) {
                 throw new moodle_exception('passwordisexpired', 'webservice');
             }
         }
         // let enrol plugins deal with new enrolments if necessary
         enrol_check_plugins($user);
         // setup user session to check capability
         session_set_user($user);
         //check if the service exists and is enabled
         $service = $DB->get_record('external_services', array('shortname' => $serviceshortname, 'enabled' => 1));
         if (empty($service)) {
             // will throw exception if no token found
             throw new moodle_exception('servicenotavailable', 'webservice');
         }
         //check if there is any required system capability
         if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) {
             throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
         }
         //specific checks related to user restricted service
         if ($service->restrictedusers) {
             $authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id, 'userid' => $user->id));
             if (empty($authoriseduser)) {
                 throw new moodle_exception('usernotallowed', 'webservice', '', $serviceshortname);
             }
             if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
                 throw new moodle_exception('invalidtimedtoken', 'webservice');
             }
             if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
                 throw new moodle_exception('invalidiptoken', 'webservice');
             }
         }
         //Check if a token has already been created for this user and this service
         //Note: this could be an admin created or an user created token.
         //      It does not really matter we take the first one that is valid.
         $tokenssql = "SELECT t.id, t.sid, t.token, t.validuntil, t.iprestriction\n              FROM {external_tokens} t\n             WHERE t.userid = ? AND t.externalserviceid = ? AND t.tokentype = ?\n          ORDER BY t.timecreated ASC";
         $tokens = $DB->get_records_sql($tokenssql, array($user->id, $service->id, EXTERNAL_TOKEN_PERMANENT));
         //A bit of sanity checks
         foreach ($tokens as $key => $token) {
             /// Checks related to a specific token. (script execution continue)
             $unsettoken = false;
             //if sid is set then there must be a valid associated session no matter the token type
             if (!empty($token->sid)) {
                 $session = session_get_instance();
                 if (!$session->session_exists($token->sid)) {
                     //this token will never be valid anymore, delete it
                     $DB->delete_records('external_tokens', array('sid' => $token->sid));
                     $unsettoken = true;
                 }
             }
             //remove token if no valid anymore
             //Also delete this wrong token (similar logic to the web service servers
             //    /webservice/lib.php/webservice_server::authenticate_by_token())
             if (!empty($token->validuntil) and $token->validuntil < time()) {
                 $DB->delete_records('external_tokens', array('token' => $token->token, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
                 $unsettoken = true;
             }
             // remove token if its ip not in whitelist
             if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
                 $unsettoken = true;
             }
             if ($unsettoken) {
                 unset($tokens[$key]);
             }
         }
         // if some valid tokens exist then use the most recent
         if (count($tokens) > 0) {
             $token = array_pop($tokens);
         } else {
             if ($serviceshortname == MOODLE_OFFICIAL_MOBILE_SERVICE and has_capability('moodle/webservice:createmobiletoken', get_system_context()) or !is_siteadmin($user) && has_capability('moodle/webservice:createtoken', get_system_context())) {
                 // if service doesn't exist, dml will throw exception
                 $service_record = $DB->get_record('external_services', array('shortname' => $serviceshortname, 'enabled' => 1), '*', MUST_EXIST);
                 // create a new token
                 $token = new stdClass();
                 $token->token = md5(uniqid(rand(), 1));
                 $token->userid = $user->id;
                 $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
                 $token->contextid = context_system::instance()->id;
                 $token->creatorid = $user->id;
                 $token->timecreated = time();
                 $token->externalserviceid = $service_record->id;
                 $tokenid = $DB->insert_record('external_tokens', $token);
                 add_to_log(SITEID, 'webservice', 'automatically create user token', '', 'User ID: ' . $user->id);
                 $token->id = $tokenid;
             } else {
                 throw new moodle_exception('cannotcreatetoken', 'webservice', '', $serviceshortname);
             }
         }
         // log token access
         $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id));
         add_to_log(SITEID, 'webservice', 'sending requested user token', '', 'User ID: ' . $user->id);
         $usertoken = new stdClass();
         $usertoken->token = $token->token;
         //complete login process by activating session.
         // To restrict the admin user to login into application
         if (is_siteadmin($user)) {
             $heIsAdmin = new stdClass();
             $heIsAdmin->error = 'admin_user';
             echo json_encode($heIsAdmin);
             die;
         }
         Login::__app_complete_user_login($user);
         $forcePasswordChangesql = "SELECT up.userid\n              FROM {user_preferences} up\n             WHERE up.userid = ? AND up.name = ? AND up.value = ?";
         $forcePasswordChange = $DB->get_records_sql($forcePasswordChangesql, array($user->id, 'auth_forcepasswordchange', 1));
         //User Update Profile starts here
         $admins = get_admins();
         $currentAdmin = end($admins);
         $admintokensql = "SELECT et.token\n              FROM {external_tokens} et\n             WHERE et.userid = ?";
         $currrentAdminToken = $DB->get_records_sql($admintokensql, array($currentAdmin->id), 0, 1);
         $unique_key = substr(md5(mt_rand(0, 1000000)), 0, 7);
         $keys = array_keys($currrentAdminToken);
         $appuser = new stdClass();
         $user->token = $token->token;
         $user->forcePasswordChange = !empty($forcePasswordChange) ? true : false;
         $user->updateProfile = substr($unique_key, 0, 3) . $keys[0] . substr($unique_key, 3, 7);
         //Get User role
         $rolesql = "SELECT id\n              FROM {role} \n             WHERE shortname = ?";
         $roleid = array_values($DB->get_records_sql($rolesql, array('reportuser')));
         $reportuser = array_values($DB->get_records_sql("SELECT id FROM {role_assignments} WHERE roleid=" . $roleid[0]->id . " AND userid=" . $user->id . ""));
         if ($reportuser[0]->id != '') {
             $user->role = 'reportuser';
         } else {
             $user->role = '';
         }
         //User Update Profile ends here
         unset($user->password);
         $appuser->USER = $user;
         $user->country_value = $user->country;
         $user->country = get_string($user->country, 'countries');
         echo json_encode($appuser);
     } else {
         throw new moodle_exception('usernamenotfound', 'moodle');
     }
 }
Ejemplo n.º 15
0
function check_user_secret($username, $passwd)
{
    $user = get_complete_user_data('username', $username);
    if (is_object($user)) {
        //  try to login this user ...
        if (!empty($passwd)) {
            return authenticate_user_login($username, $passwd);
            // returns $USER object on success
        }
    }
    return false;
}
Ejemplo n.º 16
0
    $USER->id = 0;
    require_once '../../config.php';
    print_error('auth_onelogin_saml: auth failed due to missing username/email saml attribute: ' . $pluginconfig->saml_username_map . "<br />" . get_string("auth_onelogin_saml_username_email_error", "auth_onelogin_saml") . "\r\n");
}
if ($_POST['SAMLResponse']) {
    $saml_account_matcher = $pluginconfig->saml_account_matcher;
    if (empty($saml_account_matcher)) {
        $saml_account_matcher = 'username';
    }
    $saml_create = $pluginconfig->saml_auto_create_users == 'on' ? true : false;
    $saml_update = $pluginconfig->saml_auto_update_users == 'on' ? true : false;
    $USER = auth_onelogin_saml_authenticate_user_login($saml_account_matcher, $saml_user, $saml_create, $saml_update);
} else {
    print_error("Info received. Finishing authentication process through regular method hook because no SAML response detected.");
    display_object($_POST);
    $USER = authenticate_user_login($saml_user[$saml_account_matcher], time());
}
// check that the signin worked
if ($USER == false) {
    print_error("You could not be identified or created. <br />Login result: FAILURE<br />I have...<br />" . htmlspecialchars(print_r($USER, true)));
    session_write_close();
    $USER = new object();
    $USER->id = 0;
    require_once '../../config.php';
    print_error('pluginauthfailed', 'auth_onelogin_saml', '', !empty($saml_user['username']) ? $saml_user['username'] : $saml_user['email']);
}
// complete the user login sequence
$USER->loggedin = true;
$USER->site = $CFG->wwwroot;
$USER = get_complete_user_data('id', $USER->id);
complete_user_login($USER);
Ejemplo n.º 17
0
function RWSLIMUser($r_usrn, $r_pw, $r_csf)
{
    global $RWSECAS;
    /*********** eClass Modification ************
    
        Extra Comments:
        LDAP lookup call for the employee id translation for ccid
        CCID->empid, this is needed because the authentication fails and tries to create a user.
    
        ************/
    global $CFG;
    require_once $CFG->dirroot . '/local/eclass/lib/IMS.php';
    $ims = new IMS($r_usrn, $r_pw, 'uid=', 'ou=people,dc=ualberta,dc=ca');
    $user_info = $ims->get_user_info($r_usrn);
    $empid = $user_info->employeenumber;
    /*********** End eClass Modification ********/
    if ($RWSECAS) {
        RWSPLICas($r_usrn, $r_pw, $r_csf);
    }
    //$r_usr = authenticate_user_login($r_usrn, $r_pw);
    $r_usr = authenticate_user_login($empid, $r_pw);
    //eClass Modification
    if ($r_usr) {
        complete_user_login($r_usr);
    }
    if (isloggedin()) {
        RWSSStat("1000");
    } else {
        if ($RWSECAS) {
            if (isset($_SESSION['rwscas']['cookiejar'])) {
                $r_ckf = $_SESSION['rwscas']['cookiejar'];
                if (file_exists($r_ckf)) {
                    unlink($r_ckf);
                }
                unset($_SESSION['rwscas']['cookiejar']);
            }
            unset($_SESSION['rwscas']);
        }
        RWSSErr("2008");
    }
}
Ejemplo n.º 18
0
 /**
  * @link http://docs.moodle.org/dev/Authentication_plugins#loginpage_hook.28.29
  *
  * Hook for overriding behaviour of login page.
  * Another auth hook. Process login if $authorizationcode is defined in OAuth url.
  * Makes cURL POST/GET request to social webservice and fill response data to Moodle user.
  * We check access tokens in cookies, if the ones exists - get it from $_COOKIE, if no - setcookie
  *
  * @uses $SESSION, $CFG, $DB core global objects/variables
  * @return void or @moodle_exception if OAuth request returns error or fail
  *
  * @author Igor Sazonov ( @tigusigalpa )
  */
 function loginpage_hook()
 {
     global $SESSION, $CFG, $DB;
     $access_token = false;
     $authorizationcode = optional_param('oauthcode', '', PARAM_TEXT);
     // get authorization code from url
     if (!empty($authorizationcode)) {
         $authprovider = required_param('authprovider', PARAM_TEXT);
         // get authorization provider (webservice name)
         $hack_authprovider = $authprovider == 'yahoo1' || $authprovider == 'yahoo2' ? 'yahoo' : $authprovider;
         $config_field_str = 'auth_lenauth_' . $hack_authprovider . '_social_id_field';
         $this->_field_shortname = $this->_oauth_config->{$config_field_str};
         $this->_field_id = $this->_lenauth_get_fieldid();
         $params = array();
         // params to generate data for token request
         $encode_params = true;
         $code = true;
         $redirect_uri = true;
         $curl_header = false;
         $curl_options = array();
         //if we have access_token in $_COOKIE, so do not need to make request fot the one
         $this->_send_oauth_request = !isset($_COOKIE[$authprovider]['access_token']) ? true : false;
         //if service is not enabled, why should we make request? hack protect. maybe
         $enabled_str = 'auth_lenauth_' . $hack_authprovider . '_enabled';
         if (empty($this->_oauth_config->{$enabled_str})) {
             throw new moodle_exception('Service not enabled in your LenAuth Settings', 'auth_lenauth');
         }
         switch ($authprovider) {
             case 'facebook':
                 /**
                  * @link https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.0#exchangecode
                  */
                 $params['client_id'] = $this->_oauth_config->auth_lenauth_facebook_app_id;
                 $params['client_secret'] = $this->_oauth_config->auth_lenauth_facebook_app_secret;
                 break;
             case 'google':
                 /**
                  * @link https://developers.google.com/accounts/docs/OAuth2Login#exchangecode
                  */
                 $params['client_id'] = $this->_oauth_config->auth_lenauth_google_client_id;
                 $params['client_secret'] = $this->_oauth_config->auth_lenauth_google_client_secret;
                 $params['grant_type'] = $this->_settings[$authprovider]['grant_type'];
                 break;
             case 'yahoo1':
                 if (!isset($_COOKIE[$authprovider]['access_token']) && !isset($_COOKIE[$authprovider]['oauth_verifier'])) {
                     $params = array_merge($this->_lenauth_yahoo_request_array($this->_oauth_config->auth_lenauth_yahoo_consumer_secret . '&'), array('oauth_callback' => $this->_lenauth_redirect_uri($authprovider)));
                     $code = false;
                     $redirect_uri = false;
                     $this->_send_oauth_request = isset($_REQUEST['oauth_token'], $_REQUEST['oauth_verifier']) ? false : true;
                     $oauth_verifier = false;
                     // yahoo =))
                     if (!$this->_send_oauth_request && isset($SESSION->yahoo_expires) && !empty($SESSION->yahoo_expires)) {
                         $access_token = $SESSION->yahoo_access_token = optional_param('oauth_token', '', PARAM_TEXT);
                         setcookie($authprovider . '[access_token]', $access_token, time() + $SESSION->yahoo_expires);
                         $oauth_verifier = $SESSION->yahoo_oauth_verifier = optional_param('oauth_verifier', '', PARAM_TEXT);
                         setcookie($authprovider . '[oauth_verifier]', $oauth_verifier, time() + $SESSION->yahoo_expires);
                     } else {
                     }
                 } else {
                     $this->_send_oauth_request = false;
                 }
                 break;
             case 'yahoo2':
                 $params['grant_type'] = $this->_settings[$authprovider]['grant_type'];
                 $curl_options = array('USERPWD' => $this->_oauth_config->auth_lenauth_yahoo_consumer_key . ':' . $this->_oauth_config->auth_lenauth_yahoo_consumer_secret);
                 break;
             case 'twitter':
                 if (!empty($this->_oauth_config->auth_lenauth_twitter_enabled)) {
                     if (!isset($_COOKIE[$authprovider]['access_token'])) {
                         $params = array_merge($this->_lenauth_twitter_request_array($this->_oauth_config->auth_lenauth_twitter_consumer_secret . '&'), array('oauth_callback' => $this->_lenauth_redirect_uri($authprovider)));
                         $code = false;
                         $redirect_uri = false;
                         $this->_send_oauth_request = isset($_REQUEST['oauth_token'], $_REQUEST['oauth_verifier']) ? false : true;
                         $oauth_verifier = false;
                         if (!$this->_send_oauth_request && isset($_COOKIE[$authprovider]['oauth_token_secret'])) {
                             $access_token = $SESSION->twitter_access_token = optional_param('oauth_token', '', PARAM_TEXT);
                             setcookie($authprovider . '[access_token]', $access_token, time() + $this->_settings[$authprovider]['expire'], '/');
                             $oauth_verifier = $SESSION->twitter_oauth_verifier = optional_param('oauth_verifier', '', PARAM_TEXT);
                             setcookie($authprovider . '[oauth_verifier]', $oauth_verifier, time() + $this->_settings[$authprovider]['expire'], '/');
                         } else {
                             $curl_header = $this->_lenauth_set_twitter_header($params);
                         }
                         //$curl_header = $this->_lenauth_set_twitter_header($params, $access_token/*, $oauth_token_secret = false*/);
                         /*$curl_options = array(
                               'CURLOPT_RETURNTRANSFER' => true,
                               'CURLOPT_FOLLOWLOCATION' => true
                           );
                           if ( !empty( $params['oauth_callback'] ) ) {
                               $curl_options['CURLOPT_POSTFIELDS'] = http_build_query( array() );
                           }*/
                         //TWITTER IS GOOD!!
                         $encode_params = false;
                     } else {
                         $this->_send_oauth_request = false;
                     }
                 }
                 break;
             case 'vk':
                 /**
                  * @link http://vk.com/dev/auth_sites
                  */
                 $params['client_id'] = $this->_oauth_config->auth_lenauth_vk_app_id;
                 $params['client_secret'] = $this->_oauth_config->auth_lenauth_vk_app_secret;
                 break;
             case 'yandex':
                 $params['grant_type'] = $this->_settings[$authprovider]['grant_type'];
                 $params['client_id'] = $this->_oauth_config->auth_lenauth_yandex_app_id;
                 $params['client_secret'] = $this->_oauth_config->auth_lenauth_yandex_app_password;
                 break;
             case 'mailru':
                 $params['client_id'] = $this->_oauth_config->auth_lenauth_mailru_site_id;
                 $params['client_secret'] = $this->_oauth_config->auth_lenauth_mailru_client_secret;
                 $params['grant_type'] = $this->_settings[$authprovider]['grant_type'];
                 break;
                 //odnoklassniki.ru was wrote by school programmers at 1st class and it not used mojority. bye-bye!
                 /*case 'ok':
                   $params['client_id']     = $this->_oauth_config->ok_app_id;
                   $params['client_secret'] = $this->_oauth_config->ok_secret_key;
                   break;*/
             //odnoklassniki.ru was wrote by school programmers at 1st class and it not used mojority. bye-bye!
             /*case 'ok':
               $params['client_id']     = $this->_oauth_config->ok_app_id;
               $params['client_secret'] = $this->_oauth_config->ok_secret_key;
               break;*/
             default:
                 // if authorization provider is wrong
                 throw new moodle_exception('Unknown OAuth Provider', 'auth_lenauth');
         }
         // url for catch token value
         // exception for Yahoo OAuth, because it like..
         if ($code) {
             $params['code'] = $authorizationcode;
         }
         if ($redirect_uri) {
             $params['redirect_uri'] = $this->_lenauth_redirect_uri($authprovider);
         }
         //require cURL from Moodle core
         require_once $CFG->libdir . '/filelib.php';
         // requires library with cURL class
         $curl = new curl();
         //hack for twitter and Yahoo
         if (!empty($curl_options) && is_array($curl_options)) {
             $curl->setopt($curl_options);
         }
         $curl->resetHeader();
         // clean cURL header from garbage
         //Twitter and Yahoo has an own cURL headers, so let them to be!
         if (!$curl_header) {
             $curl->setHeader('Content-Type: application/x-www-form-urlencoded');
         } else {
             $curl->setHeader($curl_header);
         }
         // cURL REQUEST for tokens if we hasnt it in $_COOKIE
         if ($this->_send_oauth_request) {
             if ($this->_curl_type == 'post') {
                 $curl_tokens_values = $curl->post($this->_settings[$authprovider]['request_token_url'], $encode_params ? $this->_generate_query_data($params) : $params);
             } else {
                 $curl_tokens_values = $curl->get($this->_settings[$authprovider]['request_token_url'] . '?' . ($encode_params ? $this->_generate_query_data($params) : $params));
             }
         }
         // check for token response
         if (!empty($curl_tokens_values) || !$this->_send_oauth_request) {
             $token_values = array();
             // parse token values
             switch ($authprovider) {
                 case 'facebook':
                     if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) {
                         parse_str($curl_tokens_values, $token_values);
                         $expires = $token_values['expires'];
                         //5183999 = 2 months
                         $access_token = $token_values['access_token'];
                         if (!empty($expires) && !empty($access_token)) {
                             setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/');
                         } else {
                             throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth');
                         }
                     } else {
                         if (isset($_COOKIE[$authprovider]['access_token'])) {
                             $access_token = $_COOKIE[$authprovider]['access_token'];
                         } else {
                             throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth');
                         }
                     }
                     break;
                 case 'google':
                     if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) {
                         $token_values = json_decode($curl_tokens_values, true);
                         $expires = $token_values['expires_in'];
                         //3600 = 1 hour
                         $access_token = $token_values['access_token'];
                         if (!empty($access_token) && !empty($expires)) {
                             setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/');
                         } else {
                             throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth');
                         }
                     } else {
                         if (isset($_COOKIE[$authprovider]['access_token'])) {
                             $access_token = $_COOKIE[$authprovider]['access_token'];
                         } else {
                             throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth');
                         }
                     }
                     break;
                 case 'yahoo1':
                     if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['oauth_token_secret'])) {
                         parse_str($curl_tokens_values, $token_values);
                         $expires = $SESSION->yahoo_expires = $token_values['oauth_expires_in'];
                         //3600 = 1 hour
                         $access_token = $SESSION->yahoo_access_token = $token_values['oauth_token'];
                         setcookie($authprovider . '[oauth_token_secret]', $token_values['oauth_token_secret'], time() + $SESSION->yahoo_expires);
                         $xoauth_request_auth_url = $token_values['xoauth_request_auth_url'];
                     } else {
                         if (isset($_COOKIE[$authprovider]['access_token'], $_COOKIE[$authprovider]['oauth_verifier']) || isset($SESSION->yahoo_access_token, $SESSION->yahoo_oauth_verifier)) {
                             $access_token = isset($_COOKIE[$authprovider]['access_token']) ? $_COOKIE[$authprovider]['access_token'] : $SESSION->yahoo_access_token;
                             $oauth_verifier = isset($_COOKIE[$authprovider]['oauth_verifier']) ? $_COOKIE[$authprovider]['oauth_verifier'] : $SESSION->yahoo_oauth_verifier;
                         } else {
                             throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth');
                         }
                     }
                     break;
                 case 'yahoo2':
                     if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) {
                         $token_values = json_decode($curl_tokens_values, true);
                         $expires = $token_values['expires_in'];
                         //3600 = 1 hour
                         $access_token = $token_values['access_token'];
                         $refresh_token = $token_values['refresh_token'];
                         $user_id = $token_values['xoauth_yahoo_guid'];
                         if (!empty($expires) && !empty($access_token)) {
                             setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/');
                             if (!empty($user_id)) {
                                 setcookie($authprovider . '[user_id]', $user_id, time() + $expires, '/');
                             }
                         } else {
                             throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth');
                         }
                     } else {
                         if (isset($_COOKIE[$authprovider]['access_token'], $_COOKIE[$authprovider]['user_id'])) {
                             $access_token = $_COOKIE[$authprovider]['access_token'];
                             $user_id = $_COOKIE[$authprovider]['user_id'];
                         } else {
                             throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth');
                         }
                     }
                     break;
                 case 'twitter':
                     if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['oauth_token_secret'])) {
                         parse_str($curl_tokens_values, $token_values);
                         $access_token = $SESSION->twitter_access_token = $token_values['oauth_token'];
                         setcookie($authprovider . '[oauth_token_secret]', $token_values['oauth_token_secret'], time() + $this->_settings[$authprovider]['expire'], '/');
                     } else {
                         if (isset($_COOKIE[$authprovider]['access_token'], $_COOKIE[$authprovider]['oauth_token_secret']) || isset($SESSION->twitter_access_token, $SESSION->twitter_oauth_verifier)) {
                             $access_token = isset($_COOKIE[$authprovider]['access_token']) ? $_COOKIE[$authprovider]['access_token'] : $SESSION->twitter_access_token;
                             $oauth_verifier = isset($_COOKIE[$authprovider]['oauth_verifier']) ? $_COOKIE[$authprovider]['oauth_verifier'] : $SESSION->twitter_oauth_verifier;
                         } else {
                             throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth');
                         }
                     }
                     break;
                 case 'vk':
                     if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) {
                         $token_values = json_decode($curl_tokens_values, true);
                         if (isset($token_values['error'])) {
                             throw new moodle_exception('Native VK Error ' . $token_values['error'] . (isset($token_values['error_description']) ? ' with description: ' . $token_values['error_description'] : ''), 'auth_lenauth');
                         }
                         $expires = $token_values['expires_in'];
                         //86400 = 24 hours
                         $access_token = $token_values['access_token'];
                         if (!empty($access_token) && !empty($expires)) {
                             setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/');
                         }
                         $user_id = $token_values['user_id'];
                         if (!empty($user_id)) {
                             setcookie($authprovider . '[user_id]', $user_id, time() + $expires, '/');
                         }
                         /**
                          * VK user may do not enter email, soooo =((
                          */
                         $user_email = isset($token_values['email']) ? $token_values['email'] : false;
                         // WOW!!! So early???))) Awesome!
                         if (!empty($user_email)) {
                             setcookie($authprovider . '[user_email]', $user_email, time() + $expires, '/');
                         }
                     } else {
                         if (isset($_COOKIE[$authprovider]['access_token'], $_COOKIE[$authprovider]['user_id'])) {
                             $access_token = $_COOKIE[$authprovider]['access_token'];
                             $user_id = $_COOKIE[$authprovider]['user_id'];
                             if (isset($_COOKIE[$authprovider]['user_email'])) {
                                 $user_email = $_COOKIE[$authprovider]['user_email'];
                             }
                         } else {
                             throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth');
                         }
                     }
                     break;
                 case 'yandex':
                     if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) {
                         $token_values = json_decode($curl_tokens_values, true);
                         $expires = $token_values['expires_in'];
                         //31536000 = 1 year
                         $access_token = $token_values['access_token'];
                         if (!empty($expires) && !empty($access_token)) {
                             setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/');
                         } else {
                             throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth');
                         }
                     } else {
                         if (isset($_COOKIE[$authprovider]['access_token'])) {
                             $access_token = $_COOKIE[$authprovider]['access_token'];
                         } else {
                             throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth');
                         }
                     }
                     break;
                 case 'mailru':
                     if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) {
                         $token_values = json_decode($curl_tokens_values, true);
                         $expires = $token_values['expires_in'];
                         //86400 = 24 hours
                         $access_token = $token_values['access_token'];
                         if (!empty($expires) && !empty($access_token)) {
                             setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/');
                         } else {
                             //check native errors if exists
                             if (isset($token_values['error'])) {
                                 switch ($token_values['error']) {
                                     case 'invalid_client':
                                         throw new moodle_exception('Mail.RU invalid OAuth settings. Check your Private Key and Secret Key', 'auth_lenauth');
                                     default:
                                         throw new moodle_exception('Mail.RU Unknown Error with code: ' . $token_values['error']);
                                 }
                             }
                             if (empty($expires) || empty($access_token)) {
                                 throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth');
                             }
                         }
                     } else {
                         if (isset($_COOKIE[$authprovider]['access_token'])) {
                             $access_token = $_COOKIE[$authprovider]['access_token'];
                         } else {
                             throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth');
                         }
                     }
                     break;
                     /*case 'ok':
                       $token_values  = json_decode( $curl_tokens_values, true );
                       $access_token  = $token_values['access_token'];
                       break;*/
                 /*case 'ok':
                   $token_values  = json_decode( $curl_tokens_values, true );
                   $access_token  = $token_values['access_token'];
                   break;*/
                 default:
                     throw new moodle_exception('Unknown OAuth Provider', 'auth_lenauth');
             }
         }
         if (!empty($access_token)) {
             $queryparams = array();
             // array to generate data for final request to get user data
             $request_api_url = $this->_settings[$authprovider]['request_api_url'];
             //some services check accounts for verifier, so we will check it too. No unverified accounts, only verified! only hardCORE!
             $is_verified = true;
             $image_url = '';
             switch ($authprovider) {
                 case 'facebook':
                     $queryparams['access_token'] = $access_token;
                     $curl_response = $curl->get($request_api_url . '?' . $this->_generate_query_data($queryparams));
                     $curl_final_data = json_decode($curl_response, true);
                     $social_uid = $curl_final_data['id'];
                     $user_email = $curl_final_data['email'];
                     $first_name = $curl_final_data['first_name'];
                     $last_name = $curl_final_data['last_name'];
                     $is_verified = $curl_final_data['verified'];
                     if ($this->_oauth_config->auth_lenauth_retrieve_avatar) {
                         $image_url = 'http://graph.facebook.com/' . $social_uid . '/picture';
                     }
                     break;
                     /**
                      * @link https://developers.google.com/accounts/docs/OAuth2Login#obtaininguserprofileinformation
                      */
                 /**
                  * @link https://developers.google.com/accounts/docs/OAuth2Login#obtaininguserprofileinformation
                  */
                 case 'google':
                     $queryparams['access_token'] = $access_token;
                     $queryparams['alt'] = 'json';
                     $curl_response = $curl->get($request_api_url . '?' . $this->_generate_query_data($queryparams));
                     $curl_final_data = json_decode($curl_response, true);
                     if (isset($curl_final_data['error'])) {
                         if (!empty($curl_final_data['error']['errors']) && is_array($curl_final_data['error']['errors'])) {
                             foreach ($curl_final_data['error']['errors'] as $error) {
                                 throw new moodle_exception('Native Google error. Message: ' . $error['message'], 'auth_lenauth');
                             }
                         } else {
                             throw new moodle_exception('Native Google error', 'auth_lenauth');
                         }
                     }
                     $social_uid = $curl_final_data['id'];
                     $user_email = $curl_final_data['emails'][0]['value'];
                     $first_name = $curl_final_data['name']['givenName'];
                     $last_name = $curl_final_data['name']['familyName'];
                     if ($this->_oauth_config->auth_lenauth_retrieve_avatar) {
                         $image_url = isset($curl_final_data['image']['url']) ? $curl_final_data['image']['url'] : '';
                     }
                     break;
                 case 'yahoo1':
                     if (!$oauth_verifier) {
                         header('Location: ' . $xoauth_request_auth_url);
                         // yahoo =))
                         die;
                     }
                     $queryparams1 = array_merge($this->_lenauth_yahoo_request_array($this->_oauth_config->auth_lenauth_yahoo_consumer_secret . '&' . $_COOKIE[$authprovider]['oauth_token_secret']), array('oauth_token' => $access_token, 'oauth_verifier' => $oauth_verifier));
                     $curl_response_pre = $curl->get($request_api_url . '?' . $this->_generate_query_data($queryparams1));
                     parse_str($curl_response_pre, $values);
                     $queryparams2 = array_merge($this->_lenauth_yahoo_request_array($this->_oauth_config->auth_lenauth_yahoo_consumer_secret . '&' . $values['oauth_token_secret']), array('oauth_token' => $values['oauth_token'], 'oauth_session_handle' => $values['oauth_session_handle']));
                     $yet_another = $curl->post($request_api_url . '?' . $this->_generate_query_data($queryparams2));
                     parse_str($yet_another, $yet_another_values);
                     $params = array('q' => 'SELECT * FROM social.profile where guid="' . $yet_another_values['xoauth_yahoo_guid'] . '"', 'format' => 'json', 'env' => 'http://datatables.org/alltables.env');
                     $auth_array = array_merge($this->_lenauth_yahoo_request_array($this->_oauth_config->auth_lenauth_yahoo_consumer_secret . '&' . $yet_another_values['oauth_token_secret']), array('realm' => 'yahooapis.com', 'oauth_token' => $yet_another_values['oauth_token']));
                     $header = '';
                     foreach ($auth_array as $key => $value) {
                         $header .= ($header === '' ? ' ' : ',') . $this->urlEncodeRfc3986($key) . '="' . $this->urlEncodeRfc3986($value) . '"';
                     }
                     $curl->setHeader(array('Expect:', 'Accept: application/json', 'Authorization: OAuth ' . $header));
                     $curl_response = $curl->post($this->_settings[$authprovider]['yql_url'] . '?' . $this->_generate_query_data($params));
                     $curl_final_data = json_decode($curl_response, true);
                     $social_uid = $curl_final_data['query']['results']['profile']['guid'];
                     $emails = $curl_final_data['query']['results']['profile']['emails'];
                     if (!empty($emails) && is_array($emails)) {
                         foreach ($emails as $email_array) {
                             $user_email = $email_array['handle'];
                             if (isset($email_array['primary'])) {
                                 break;
                             }
                         }
                     }
                     $first_name = $curl_final_data['query']['results']['profile']['givenName'];
                     $last_name = $curl_final_data['query']['results']['profile']['familyName'];
                     if ($this->_oauth_config->auth_lenauth_retrieve_avatar) {
                         $image_url = isset($curl_final_data['query']['results']['profile']['image']['imageUrl']) ? $curl_final_data['query']['results']['profile']['image']['imageUrl'] : '';
                     }
                     break;
                 case 'yahoo2':
                     $request_api_url = 'https://social.yahooapis.com/v1/user/' . $user_id . '/profile?format=json';
                     $queryparams['access_token'] = $access_token;
                     $now_header = array('Authorization: Bearer ' . $access_token, 'Accept: application/json', 'Content-Type: application/json');
                     $curl->resetHeader();
                     $curl->setHeader($now_header);
                     $curl_response = $curl->get($request_api_url, $queryparams);
                     $curl->resetHeader();
                     $curl_final_data = json_decode($curl_response, true);
                     $social_uid = $curl_final_data['profile']['guid'];
                     $emails = $curl_final_data['profile']['emails'];
                     if (!empty($emails) && is_array($emails)) {
                         foreach ($emails as $email_array) {
                             $user_email = $email_array['handle'];
                             if (isset($email_array['primary'])) {
                                 break;
                             }
                         }
                     }
                     $first_name = $curl_final_data['profile']['givenName'];
                     $last_name = $curl_final_data['profile']['familyName'];
                     if ($this->_oauth_config->auth_lenauth_retrieve_avatar) {
                         $image_url = isset($curl_final_data['profile']['image']['imageUrl']) ? $curl_final_data['profile']['image']['imageUrl'] : '';
                     }
                     break;
                 case 'twitter':
                     if (!$oauth_verifier) {
                         header('Location: ' . $this->_settings[$authprovider]['request_api_url'] . '?' . http_build_query(array('oauth_token' => $access_token)));
                         die;
                     }
                     $queryparams = array_merge($this->_lenauth_twitter_request_array(), array('oauth_verifier' => $oauth_verifier, 'oauth_token' => $access_token, 'oauth_token_secret' => $_COOKIE[$authprovider]['oauth_token_secret']));
                     $curl_header = $this->_lenauth_set_twitter_header($queryparams, $access_token, $_COOKIE[$authprovider]['oauth_token_secret']);
                     $curl->setHeader($curl_header);
                     $curl_final_data_pre = $curl->post($this->_settings[$authprovider]['token_url'], $queryparams);
                     $json_decoded = json_decode($curl_final_data_pre, true);
                     if (isset($json_decoded['error']) && isset($json_decoded['request'])) {
                         throw new moodle_exception('Native Twitter Error: ' . $json_decoded['error'] . '. For request ' . $json_decoded['request'], 'auth_lenauth');
                     }
                     parse_str($curl_final_data_pre, $curl_final_data);
                     $social_uid = $curl_final_data['user_id'];
                     if ($this->_oauth_config->auth_lenauth_retrieve_avatar) {
                         $image_url_pre = 'https://twitter.com/' . $curl_final_data['screen_name'] . '/profile_image?size=original';
                         $image_header = get_headers($image_url_pre, 1);
                         $image_url = $image_header['location'];
                     }
                     break;
                 case 'vk':
                     /**
                      * @link http://vk.com/dev/api_requests
                      */
                     $queryparams['access_token'] = $access_token;
                     $queryparams['user_id'] = !empty($user_id) ? $user_id : false;
                     $queryparams['v'] = self::$vk_api_version;
                     $curl_response = $curl->post($request_api_url, $this->_generate_query_data($queryparams));
                     $curl_final_data = json_decode($curl_response, true);
                     //$social_uid                  = ( isset( $user_id ) ) ? $user_id : $curl_final_data['response'][0]['id']; //dont forget about this
                     $social_uid = $queryparams['user_id'];
                     /**
                      * If user_email is empty, its not so scare, because its second login and 
                      */
                     $user_email = isset($user_email) ? $user_email : false;
                     //hack, because VK has bugs sometimes
                     $first_name = $curl_final_data['response'][0]['first_name'];
                     $last_name = $curl_final_data['response'][0]['last_name'];
                     /**
                      * @link http://vk.com/dev/users.get
                      */
                     $fields_array = array('avatar' => 'photo_200');
                     $additional_fields_pre = $curl->get('http://api.vk.com/method/users.get?user_ids=' . $social_uid . '&fields=' . join(',', $fields_array));
                     $additional_fields = json_decode($additional_fields_pre, true);
                     if ($this->_oauth_config->auth_lenauth_retrieve_avatar) {
                         $image_url = isset($additional_fields['response'][0][$fields_array['avatar']]) ? $additional_fields['response'][0][$fields_array['avatar']] : '';
                     }
                     break;
                     /**
                      * @link http://api.yandex.ru/oauth/doc/dg/reference/accessing-protected-resource.xml
                      * @link http://api.yandex.ru/login/doc/dg/reference/request.xml
                      */
                 /**
                  * @link http://api.yandex.ru/oauth/doc/dg/reference/accessing-protected-resource.xml
                  * @link http://api.yandex.ru/login/doc/dg/reference/request.xml
                  */
                 case 'yandex':
                     $queryparams['format'] = $this->_settings[$authprovider]['format'];
                     $queryparams['oauth_token'] = $access_token;
                     $curl_response = $curl->get($request_api_url . '?' . $this->_generate_query_data($queryparams));
                     $curl_final_data = json_decode($curl_response, true);
                     $social_uid = $curl_final_data['id'];
                     /**
                      * fix @since 24.12.2014. Thanks for Yandex Tech team guys!!
                      * @link https://tech.yandex.ru/passport/
                      */
                     $user_email = $curl_final_data['default_email'];
                     //was $curl_final_data['emails'][0]; - wrong!
                     $first_name = $curl_final_data['first_name'];
                     $last_name = $curl_final_data['last_name'];
                     $nickname = $curl_final_data['display_name'];
                     //for future
                     if ($this->_oauth_config->auth_lenauth_retrieve_avatar) {
                         /**
                          * @link https://tech.yandex.ru/passport/doc/dg/reference/response-docpage/#norights_5
                          */
                         $yandex_avatar_size = 'islands-200';
                         if (isset($curl_final_data['default_avatar_id'])) {
                             $image_url = 'https://avatars.yandex.net/get-yapic/' . $curl_final_data['default_avatar_id'] . '/' . $yandex_avatar_size;
                         }
                     }
                     break;
                 case 'mailru':
                     $queryparams['app_id'] = $params['client_id'];
                     $secret_key = $params['client_secret'];
                     /**
                      * @link http://api.mail.ru/docs/reference/rest/users-getinfo/
                      */
                     $queryparams['method'] = 'users.getInfo';
                     $queryparams['session_key'] = $access_token;
                     $queryparams['secure'] = 1;
                     /**
                      * Additional security from mail.ru
                      * @link http://api.mail.ru/docs/guides/restapi/#sig
                      */
                     ksort($queryparams);
                     $sig = '';
                     foreach ($queryparams as $k => $v) {
                         $sig .= "{$k}={$v}";
                     }
                     $queryparams['sig'] = md5($sig . $secret_key);
                     $curl_response = $curl->post($request_api_url, $this->_generate_query_data($queryparams));
                     $curl_final_data = json_decode($curl_response, true);
                     $social_uid = $curl_final_data[0]['uid'];
                     $user_email = $curl_final_data[0]['email'];
                     $first_name = $curl_final_data[0]['first_name'];
                     $last_name = $curl_final_data[0]['last_name'];
                     $is_verified = $curl_final_data[0]['is_verified'];
                     $birthday = $curl_final_data[0]['birthday'];
                     //dd.mm.YYYY
                     if ($this->_oauth_config->auth_lenauth_retrieve_avatar) {
                         $image_url = isset($curl_final_data[0]['pic_big']) ? $curl_final_data[0]['pic_big'] : '';
                     }
                     break;
                     /*case 'ok':
                                             $queryparams['access_token'] = $access_token;
                                             $queryparams['method']       = 'users.getCurrentUser';
                                             $queryparams['sig']          = md5( 'application_key=' . $this->_oauth_config->ok_public_key . 'method=' . $queryparams['method'] . md5( $queryparams['access_token'] . $this->_oauth_config->ok_secret_key ) );
                                             $queryparams['application_key'] = $this->_oauth_config->ok_public_key;
                                             $curl_response               = $curl->get( $request_api_url . '?' . $this->_generate_query_data( $queryparams ) );
                                             $curl_final_data             = json_decode( $curl_response, true );
                     
                                             $first_name                  = $curl_final_data['first_name'];
                                             $last_name                   = $curl_final_data['last_name'];
                                             $social_uid                  = $curl_final_data['uid'];
                                             break;*/
                 /*case 'ok':
                                         $queryparams['access_token'] = $access_token;
                                         $queryparams['method']       = 'users.getCurrentUser';
                                         $queryparams['sig']          = md5( 'application_key=' . $this->_oauth_config->ok_public_key . 'method=' . $queryparams['method'] . md5( $queryparams['access_token'] . $this->_oauth_config->ok_secret_key ) );
                                         $queryparams['application_key'] = $this->_oauth_config->ok_public_key;
                                         $curl_response               = $curl->get( $request_api_url . '?' . $this->_generate_query_data( $queryparams ) );
                                         $curl_final_data             = json_decode( $curl_response, true );
                 
                                         $first_name                  = $curl_final_data['first_name'];
                                         $last_name                   = $curl_final_data['last_name'];
                                         $social_uid                  = $curl_final_data['uid'];
                                         break;*/
                 default:
                     throw new moodle_exception('Unknown OAuth Provider', 'auth_lenauth');
             }
             /**
              * Check for email returned by webservice. If exist - check for user with this email in Moodle Database
              */
             if (!empty($curl_final_data)) {
                 if (!empty($social_uid)) {
                     if ($is_verified) {
                         if (!empty($user_email)) {
                             if ($err = email_is_not_allowed($user_email)) {
                                 throw new moodle_exception($err, 'auth_lenauth');
                             }
                             $user_lenauth = $DB->get_record('user', array('email' => $user_email, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id));
                         } else {
                             if (empty($user_lenauth)) {
                                 $user_lenauth = $this->_lenauth_get_userdata_by_social_id($social_uid);
                             }
                             /*if ( empty( $user_lenauth ) ) {
                                   $user_lenauth = $DB->get_record('user', array('username' => $username, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id));
                               }*/
                         }
                     } else {
                         throw new moodle_exception('Your social account is not verified', 'auth_lenauth');
                     }
                 } else {
                     throw new moodle_exception('Empty Social UID', 'auth_lenauth');
                 }
             } else {
                 /**
                  * addon @since 24.12.2014
                  * I forgot about clear $_COOKIE, thanks again for Yandex Tech Team guys!!!
                  */
                 @setcookie($authprovider, null, time() - 3600);
                 throw new moodle_exception('Final request returns nothing', 'auth_lenauth');
             }
             $last_user_number = intval($this->_oauth_config->auth_lenauth_last_user_number);
             $last_user_number = empty($last_user_number) ? 1 : $last_user_number + 1;
             //$username = $this->_oauth_config->auth_lenauth_user_prefix . $last_user_number; //@todo
             /**
              * If user with email from webservice not exists, we will create an account
              */
             if (empty($user_lenauth)) {
                 $username = $this->_oauth_config->auth_lenauth_user_prefix . $last_user_number;
                 //check for username exists in DB
                 $user_lenauth_check = $DB->get_record('user', array('username' => $username));
                 $i_check = 0;
                 while (!empty($user_lenauth_check)) {
                     $user_lenauth_check = $user_lenauth_check + 1;
                     $username = $this->_oauth_config->auth_lenauth_user_prefix . $last_user_number;
                     $user_lenauth_check = $DB->get_record('user', array('username' => $username));
                     $i_check++;
                     if ($i_check > 20) {
                         throw new moodle_exception('Something wrong with usernames of LenAuth users. Limit of 20 queries is out. Check last mdl_user table of Moodle', 'auth_lenauth');
                     }
                 }
                 // create user HERE
                 $user_lenauth = create_user_record($username, '', 'lenauth');
                 /**
                  * User exists...
                  */
             } else {
                 $username = $user_lenauth->username;
             }
             set_config('auth_lenauth_last_user_number', $last_user_number, 'auth/lenauth');
             if (!empty($social_uid)) {
                 $user_social_uid_custom_field = new stdClass();
                 $user_social_uid_custom_field->userid = $user_lenauth->id;
                 $user_social_uid_custom_field->fieldid = $this->_field_id;
                 $user_social_uid_custom_field->data = $social_uid;
                 if (!$DB->record_exists('user_info_data', array('userid' => $user_lenauth->id, 'fieldid' => $this->_field_id))) {
                     $DB->insert_record('user_info_data', $user_social_uid_custom_field);
                 } else {
                     $record = $DB->get_record('user_info_data', array('userid' => $user_lenauth->id, 'fieldid' => $this->_field_id));
                     $user_social_uid_custom_field->id = $record->id;
                     $DB->update_record('user_info_data', $user_social_uid_custom_field);
                 }
             }
             //add_to_log( SITEID, 'auth_lenauth', '', '', $username . '/' . $user_email . '/' . $userid );
             // complete Authenticate user
             authenticate_user_login($username, null);
             // fill $newuser object with response data from webservices
             $newuser = new stdClass();
             if (!empty($user_email)) {
                 $newuser->email = $user_email;
             }
             if (!empty($first_name)) {
                 $newuser->firstname = $first_name;
             }
             if (!empty($last_name)) {
                 $newuser->lastname = $last_name;
             }
             if (!empty($this->_oauth_config->auth_lenauth_default_country)) {
                 $newuser->country = $this->_oauth_config->auth_lenauth_default_country;
             }
             if ($user_lenauth) {
                 // update user record
                 if (!empty($newuser)) {
                     $newuser->id = $user_lenauth->id;
                     /*require_once( $CFG->libdir . '/gdlib.php' );
                     
                                                 $fs = get_file_storage();
                                                 $file_obj = $fs->create_file_from_url( array(
                                                     'contextid' => context_user::instance( $newuser->id, MUST_EXIST )->id,
                                                     'component' => 'user',
                                                     'filearea'  => 'icon',
                                                     'itemid'    => 0,
                                                     'filepath'  => '/',
                                                     'source'    => '',
                                                     'filename'  => 'f' . $newuser->id . '.' . $ext
                                                 ), $image_url );
                                                 //$newuser->picture = $file_obj->get_id();*/
                     $user_lenauth = (object) array_merge((array) $user_lenauth, (array) $newuser);
                     $DB->update_record('user', $user_lenauth);
                     if ($this->_oauth_config->auth_lenauth_retrieve_avatar) {
                         //processing user avatar from social webservice
                         if (!empty($image_url) && intval($user_lenauth->picture) === 0) {
                             $image_header = get_headers($image_url, 1);
                             if (isset($image_header['Content-Type']) && is_string($image_header['Content-Type']) && in_array($image_header['Content-Type'], array_keys(self::$_allowed_icons_types))) {
                                 $mime = $image_header['Content-Type'];
                             } else {
                                 if (isset($image_header['Content-Type'][0]) && is_string($image_header['Content-Type'][0]) && in_array($image_header['Content-Type'][0], array_keys(self::$_allowed_icons_types))) {
                                     $mime = $image_header['Content-Type'][0];
                                 }
                             }
                             $ext = $this->_lenauth_get_image_extension_from_mime($mime);
                             if ($ext) {
                                 //create temp file
                                 $tempfilename = substr(microtime(), 0, 10) . '.tmp';
                                 $templfolder = $CFG->tempdir . '/filestorage';
                                 if (!file_exists($templfolder)) {
                                     mkdir($templfolder, $CFG->directorypermissions);
                                 }
                                 @chmod($templfolder, 0777);
                                 $tempfile = $templfolder . '/' . $tempfilename;
                                 if (copy($image_url, $tempfile)) {
                                     require_once $CFG->libdir . '/gdlib.php';
                                     $usericonid = process_new_icon(context_user::instance($newuser->id, MUST_EXIST), 'user', 'icon', 0, $tempfile);
                                     if ($usericonid) {
                                         $DB->set_field('user', 'picture', $usericonid, array('id' => $newuser->id));
                                     }
                                     unset($tempfile);
                                 }
                                 @chmod($templfolder, $CFG->directorypermissions);
                             }
                         }
                     }
                 }
                 complete_user_login($user_lenauth);
                 // complete user login
                 // Redirection
                 $urltogo = $CFG->wwwroot;
                 if (user_not_fully_set_up($user_lenauth)) {
                     $urltogo = $CFG->wwwroot . '/user/edit.php';
                 } else {
                     if (isset($SESSION->wantsurl) && strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) {
                         $urltogo = $SESSION->wantsurl;
                         unset($SESSION->wantsurl);
                     } else {
                         unset($SESSION->wantsurl);
                     }
                 }
             }
             redirect($urltogo);
         } else {
             throw new moodle_exception('Could not get access to access token. Check your App Settings', 'auth_lenauth');
         }
     }
 }
Ejemplo n.º 19
0
 /**
  * Find the session set by ntlmsso_magic(), validate it and 
  * call authenticate_user_login() to authenticate the user through
  * the auth machinery.
  * 
  * It is complemented by a similar check in user_login().
  * 
  * If it succeeds, it never returns. 
  *
  */
 function ntlmsso_finish()
 {
     global $CFG, $USER, $SESSION;
     $key = sesskey();
     $cf = get_cache_flags('auth/ldap/ntlmsess');
     if (!isset($cf[$key]) || $cf[$key] === '') {
         return false;
     }
     $username = $cf[$key];
     // Here we want to trigger the whole authentication machinery
     // to make sure no step is bypassed...
     $user = authenticate_user_login($username, $key);
     if ($user) {
         add_to_log(SITEID, 'user', 'login', "view.php?id={$USER->id}&course=" . SITEID, $user->id, 0, $user->id);
         $USER = complete_user_login($user);
         // Cleanup the key to prevent reuse...
         // and to allow re-logins with normal credentials
         unset_cache_flag('auth/ldap/ntlmsess', $key);
         /// Redirection
         if (user_not_fully_set_up($USER)) {
             $urltogo = $CFG->wwwroot . '/user/edit.php';
             // We don't delete $SESSION->wantsurl yet, so we get there later
         } else {
             if (isset($SESSION->wantsurl) and strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) {
                 $urltogo = $SESSION->wantsurl;
                 /// Because it's an address in this site
                 unset($SESSION->wantsurl);
             } else {
                 // no wantsurl stored or external - go to homepage
                 $urltogo = $CFG->wwwroot . '/';
                 unset($SESSION->wantsurl);
             }
         }
         redirect($urltogo);
     }
     // Should never reach here.
     return false;
 }
Ejemplo n.º 20
0
 /**
  * Authentication hook - is called every time user hit the login page
  * The code is run only if the param code is mentionned.
  */
 public function loginpage_hook()
 {
     global $USER, $SESSION, $CFG, $DB;
     // Check the Google authorization code.
     $authorizationcode = optional_param('code', '', PARAM_TEXT);
     if (!empty($authorizationcode)) {
         $authprovider = required_param('authprovider', PARAM_ALPHANUMEXT);
         require_once $CFG->dirroot . '/auth/googleoauth2/classes/provider/' . $authprovider . '.php';
         $providerclassname = 'provideroauth2' . $authprovider;
         $provider = new $providerclassname();
         // Try to get an access token (using the authorization code grant).
         $token = $provider->getAccessToken('authorization_code', ['code' => $authorizationcode]);
         $accesstoken = $token->accessToken;
         $refreshtoken = $token->refreshToken;
         $tokenexpires = $token->expires;
         // With access token request by curl the email address.
         if (!empty($accesstoken)) {
             try {
                 // We got an access token, let's now get the user's details.
                 $userdetails = $provider->getUserDetails($token);
                 // Use these details to create a new profile.
                 switch ($authprovider) {
                     case 'battlenet':
                         // Battlenet as no email notion.
                         // TODO: need to check the idp table for matching user and request user to add his email.
                         // TODO: It will be similar logic for twitter.
                         $useremail = $userdetails->id . '@fakebattle.net';
                         break;
                     case 'github':
                         $useremails = $provider->getUserEmails($token);
                         // Going to try to find someone with a similar email using googleoauth2 auth.
                         $fallbackuseremail = '';
                         foreach ($useremails as $githubuseremail) {
                             if ($githubuseremail->verified) {
                                 if ($DB->record_exists('user', array('auth' => 'googleoauth2', 'email' => $githubuseremail->email))) {
                                     $useremail = $githubuseremail->email;
                                 }
                                 $fallbackuseremail = $githubuseremail->email;
                             }
                         }
                         // If we didn't find anyone then we take a verified email address.
                         if (empty($useremail)) {
                             $useremail = $fallbackuseremail;
                         }
                         break;
                     case 'vk':
                         // VK doesn't return the email address?
                         if ($userdetails->uid) {
                             $useremail = 'id' . $userdetails->uid . '@vkmessenger.com';
                         }
                         break;
                     default:
                         $useremail = $userdetails->email;
                         break;
                 }
                 $verified = 1;
             } catch (Exception $e) {
                 // Failed to get user details.
                 throw new moodle_exception('faileduserdetails', 'auth_googleoauth2');
             }
             // Throw an error if the email address is not verified.
             if (!$verified) {
                 throw new moodle_exception('emailaddressmustbeverified', 'auth_googleoauth2');
             }
             // Prohibit login if email belongs to the prohibited domain.
             if ($err = email_is_not_allowed($useremail)) {
                 throw new moodle_exception($err, 'auth_googleoauth2');
             }
             // If email not existing in user database then create a new username (userX).
             if (empty($useremail) or $useremail != clean_param($useremail, PARAM_EMAIL)) {
                 throw new moodle_exception('couldnotgetuseremail', 'auth_googleoauth2');
                 // TODO: display a link for people to retry.
             }
             // Get the user.
             // Don't bother with auth = googleoauth2 because authenticate_user_login() will fail it if it's not 'googleoauth2'.
             $user = $DB->get_record('user', array('email' => $useremail, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id));
             // Create the user if it doesn't exist.
             if (empty($user)) {
                 // Deny login if setting "Prevent account creation when authenticating" is on.
                 if ($CFG->authpreventaccountcreation) {
                     throw new moodle_exception("noaccountyet", "auth_googleoauth2");
                 }
                 // Get following incremented username.
                 $googleuserprefix = core_text::strtolower(get_config('auth/googleoauth2', 'googleuserprefix'));
                 $lastusernumber = get_config('auth/googleoauth2', 'lastusernumber');
                 $lastusernumber = empty($lastusernumber) ? 1 : $lastusernumber + 1;
                 // Check the user doesn't exist.
                 $nextuser = $DB->record_exists('user', array('username' => $googleuserprefix . $lastusernumber));
                 while ($nextuser) {
                     $lastusernumber++;
                     $nextuser = $DB->record_exists('user', array('username' => $googleuserprefix . $lastusernumber));
                 }
                 set_config('lastusernumber', $lastusernumber, 'auth/googleoauth2');
                 $username = $googleuserprefix . $lastusernumber;
                 // Retrieve more information from the provider.
                 $newuser = new stdClass();
                 $newuser->email = $useremail;
                 switch ($authprovider) {
                     case 'battlenet':
                         // Battlenet as no firstname/lastname notion.
                         $newuser->firstname = $userdetails->display_name;
                         $newuser->lastname = '[' . $userdetails->clan_tag . ']';
                         break;
                     case 'github':
                     case 'dropbox':
                         // As Github/Dropbox doesn't provide firstname/lastname, we'll split the name at the first whitespace.
                         $githubusername = explode(' ', $userdetails->name, 2);
                         $newuser->firstname = $githubusername[0];
                         $newuser->lastname = $githubusername[1];
                         break;
                     default:
                         $newuser->firstname = $userdetails->firstName;
                         $newuser->lastname = $userdetails->lastName;
                         break;
                 }
                 // Some providers allow empty firstname and lastname.
                 if (empty($newuser->firstname)) {
                     $newuser->firstname = get_string('unknownfirstname', 'auth_googleoauth2');
                 }
                 if (empty($newuser->lastname)) {
                     $newuser->lastname = get_string('unknownlastname', 'auth_googleoauth2');
                 }
                 // Retrieve country and city if the provider failed to give it.
                 if (!isset($newuser->country) or !isset($newuser->city)) {
                     $googleipinfodbkey = get_config('auth/googleoauth2', 'googleipinfodbkey');
                     if (!empty($googleipinfodbkey)) {
                         require_once $CFG->libdir . '/filelib.php';
                         $curl = new curl();
                         $locationdata = $curl->get('http://api.ipinfodb.com/v3/ip-city/?key=' . $googleipinfodbkey . '&ip=' . getremoteaddr() . '&format=json');
                         $locationdata = json_decode($locationdata);
                     }
                     if (!empty($locationdata)) {
                         // TODO: check that countryCode does match the Moodle country code.
                         $newuser->country = isset($newuser->country) ? isset($newuser->country) : $locationdata->countryCode;
                         $newuser->city = isset($newuser->city) ? isset($newuser->city) : $locationdata->cityName;
                     }
                 }
                 create_user_record($username, '', 'googleoauth2');
             } else {
                 $username = $user->username;
             }
             // Authenticate the user.
             // TODO: delete this log later.
             require_once $CFG->dirroot . '/auth/googleoauth2/lib.php';
             $userid = empty($user) ? 'new user' : $user->id;
             oauth_add_to_log(SITEID, 'auth_googleoauth2', '', '', $username . '/' . $useremail . '/' . $userid);
             $user = authenticate_user_login($username, null);
             if ($user) {
                 // Set a cookie to remember what auth provider was selected.
                 setcookie('MOODLEGOOGLEOAUTH2_' . $CFG->sessioncookie, $authprovider, time() + DAYSECS * 60, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
                 // Prefill more user information if new user.
                 if (!empty($newuser)) {
                     $newuser->id = $user->id;
                     $DB->update_record('user', $newuser);
                     $user = (object) array_merge((array) $user, (array) $newuser);
                 }
                 complete_user_login($user);
                 // Let's save/update the access token for this user.
                 $cansaveaccesstoken = get_config('auth/googleoauth2', 'saveaccesstoken');
                 if (!empty($cansaveaccesstoken)) {
                     $existingaccesstoken = $DB->get_record('auth_googleoauth2_user_idps', array('userid' => $user->id, 'provider' => $authprovider));
                     if (empty($existingaccesstoken)) {
                         $accesstokenrow = new stdClass();
                         $accesstokenrow->userid = $user->id;
                         switch ($authprovider) {
                             case 'battlenet':
                                 $accesstokenrow->provideruserid = $userdetails->id;
                                 break;
                             default:
                                 $accesstokenrow->provideruserid = $userdetails->uid;
                                 break;
                         }
                         $accesstokenrow->provider = $authprovider;
                         $accesstokenrow->accesstoken = $accesstoken;
                         $accesstokenrow->refreshtoken = $refreshtoken;
                         $accesstokenrow->expires = $tokenexpires;
                         $DB->insert_record('auth_googleoauth2_user_idps', $accesstokenrow);
                     } else {
                         $existingaccesstoken->accesstoken = $accesstoken;
                         $DB->update_record('auth_googleoauth2_user_idps', $existingaccesstoken);
                     }
                 }
                 // Check if the user picture is the default and retrieve the provider picture.
                 if (empty($user->picture)) {
                     switch ($authprovider) {
                         case 'battlenet':
                             require_once $CFG->libdir . '/filelib.php';
                             require_once $CFG->libdir . '/gdlib.php';
                             $imagefilename = $CFG->tempdir . '/googleoauth2-portrait-' . $user->id;
                             $imagecontents = download_file_content($userdetails->portrait_url);
                             file_put_contents($imagefilename, $imagecontents);
                             if ($newrev = process_new_icon(context_user::instance($user->id), 'user', 'icon', 0, $imagefilename)) {
                                 $DB->set_field('user', 'picture', $newrev, array('id' => $user->id));
                             }
                             unlink($imagefilename);
                             break;
                         default:
                             // TODO retrieve other provider profile pictures.
                             break;
                     }
                 }
                 // Create event for authenticated user.
                 $event = \auth_googleoauth2\event\user_loggedin::create(array('context' => context_system::instance(), 'objectid' => $user->id, 'relateduserid' => $user->id, 'other' => array('accesstoken' => $accesstoken)));
                 $event->trigger();
                 // Redirection.
                 if (user_not_fully_set_up($USER)) {
                     $urltogo = $CFG->wwwroot . '/user/edit.php';
                     // We don't delete $SESSION->wantsurl yet, so we get there later.
                 } else {
                     if (isset($SESSION->wantsurl) and strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) {
                         $urltogo = $SESSION->wantsurl;
                         // Because it's an address in this site.
                         unset($SESSION->wantsurl);
                     } else {
                         // No wantsurl stored or external - go to homepage.
                         $urltogo = $CFG->wwwroot . '/';
                         unset($SESSION->wantsurl);
                     }
                 }
                 $loginrecord = array('userid' => $USER->id, 'time' => time(), 'auth' => 'googleoauth2', 'subtype' => $authprovider);
                 $DB->insert_record('auth_googleoauth2_logins', $loginrecord);
                 redirect($urltogo);
             } else {
                 // Authenticate_user_login() failure, probably email registered by another auth plugin.
                 // Do a check to confirm this hypothesis.
                 $userexist = $DB->get_record('user', array('email' => $useremail));
                 if (!empty($userexist) and $userexist->auth != 'googleoauth2') {
                     $a = new stdClass();
                     $a->loginpage = (string) new moodle_url(empty($CFG->alternateloginurl) ? '/login/index.php' : $CFG->alternateloginurl);
                     $a->forgotpass = (string) new moodle_url('/login/forgot_password.php');
                     throw new moodle_exception('couldnotauthenticateuserlogin', 'auth_googleoauth2', '', $a);
                 } else {
                     throw new moodle_exception('couldnotauthenticate', 'auth_googleoauth2');
                 }
             }
         } else {
             throw new moodle_exception('couldnotgetgoogleaccesstoken', 'auth_googleoauth2');
         }
     } else {
         // If you are having issue with the display buttons option, add the button code directly in the theme login page.
         if (get_config('auth/googleoauth2', 'oauth2displaybuttons') and empty($_POST['username']) and empty($_POST['password'])) {
             // Display the button on the login page.
             require_once $CFG->dirroot . '/auth/googleoauth2/lib.php';
             // Insert the html code below the login field.
             // Code/Solution from Elcentra plugin: https://moodle.org/plugins/view/auth_elcentra.
             global $PAGE, $CFG;
             $PAGE->requires->jquery();
             $content = str_replace(array("\n", "\r"), array("\\\n", "\\\r"), auth_googleoauth2_display_buttons(false));
             $PAGE->requires->css('/auth/googleoauth2/style.css');
             $PAGE->requires->js_init_code("buttonsCodeOauth2 = '{$content}';");
             $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/googleoauth2/script.js"));
         }
     }
 }
Ejemplo n.º 21
0
define('AJAX_SCRIPT', true);
define('REQUIRE_CORRECT_ACCESS', true);
define('NO_MOODLE_COOKIES', true);
require_once dirname(dirname(__FILE__)) . '/config.php';
$username = required_param('username', PARAM_USERNAME);
$password = required_param('password', PARAM_RAW);
$serviceshortname = required_param('service', PARAM_ALPHANUMEXT);
echo $OUTPUT->header();
if (!$CFG->enablewebservices) {
    throw new moodle_exception('enablewsdescription', 'webservice');
}
$username = trim(core_text::strtolower($username));
if (is_restored_user($username)) {
    throw new moodle_exception('restoredaccountresetpassword', 'webservice');
}
$user = authenticate_user_login($username, $password);
if (!empty($user)) {
    //Non admin can not authenticate if maintenance mode
    $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
    if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
        throw new moodle_exception('sitemaintenance', 'admin');
    }
    if (isguestuser($user)) {
        throw new moodle_exception('noguest');
    }
    if (empty($user->confirmed)) {
        throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
    }
    // check credential expiry
    $userauth = get_auth_plugin($user->auth);
    if (!empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
Ejemplo n.º 22
0
 public function generate_data()
 {
     if (is_null($this->get('username')) || $this->get('username') == '') {
         echo "You must enter a valid username for a moodle administrator account on this site.{$this->eolchar}";
         die;
     } elseif (is_null($this->get('password')) || $this->get('password') == '') {
         echo "You must enter a valid password for a moodle administrator account on this site.{$this->eolchar}";
         die;
     } else {
         if (!($user = authenticate_user_login($this->get('username'), $this->get('password')))) {
             echo "Invalid username or password!{$this->eolchar}";
             die;
         }
         complete_user_login($user);
         $systemcontext = get_context_instance(CONTEXT_SYSTEM);
         if (!is_siteadmin($user->id)) {
             //TODO: add some proper access control check here!!
             echo "You do not have administration privileges on this Moodle site. " . "These are required for running the generation script.{$this->eolchar}";
             die;
         }
     }
     parent::generate_data();
 }
Ejemplo n.º 23
0
    } else {
        $mform->display();
    }
    $web_interface = true;
}
if ($run_script) {
    // User authentication
    if (!$web_interface) {
        if (empty($settings['username'])) {
            echo "You must enter a valid username for a moodle administrator account on this site.{$settings['eolchar']}";
            die;
        } elseif (empty($settings['password'])) {
            echo "You must enter a valid password for a moodle administrator account on this site.{$settings['eolchar']}";
            die;
        } else {
            if (!($user = authenticate_user_login($settings['username'], $settings['password']))) {
                echo "Invalid username or password!{$settings['eolchar']}";
                die;
            }
            $USER = complete_user_login($user);
            if (!has_capability('moodle/site:doanything', $systemcontext)) {
                echo "You do not have administration privileges on this Moodle site. These are required for running the restore script.{$settings['eolchar']}";
                die;
            }
        }
    }
    // Script code here
    // Look for old moodledata/users directory
    $oldusersdir = $CFG->dataroot . '/users';
    if (!file_exists($oldusersdir)) {
        notify('The old directory for user profile images (' . $oldusersdir . ') does not exist. Pictures cannot be restored!');
Ejemplo n.º 24
0
 /**
  * Find the session set by ntlmsso_magic(), validate it and
  * call authenticate_user_login() to authenticate the user through
  * the auth machinery.
  *
  * It is complemented by a similar check in user_login().
  *
  * If it succeeds, it never returns.
  *
  */
 function ntlmsso_finish()
 {
     global $CFG, $USER, $SESSION;
     $key = sesskey();
     $cf = get_cache_flags($this->pluginconfig . '/ntlmsess');
     if (!isset($cf[$key]) || $cf[$key] === '') {
         return false;
     }
     $username = $cf[$key];
     // Here we want to trigger the whole authentication machinery
     // to make sure no step is bypassed...
     $user = authenticate_user_login($username, $key);
     if ($user) {
         complete_user_login($user);
         // Cleanup the key to prevent reuse...
         // and to allow re-logins with normal credentials
         unset_cache_flag($this->pluginconfig . '/ntlmsess', $key);
         // Redirection
         if (user_not_fully_set_up($USER)) {
             $urltogo = $CFG->wwwroot . '/user/edit.php';
             // We don't delete $SESSION->wantsurl yet, so we get there later
         } else {
             if (isset($SESSION->wantsurl) and strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) {
                 $urltogo = $SESSION->wantsurl;
                 // Because it's an address in this site
                 unset($SESSION->wantsurl);
             } else {
                 // No wantsurl stored or external - go to homepage
                 $urltogo = $CFG->wwwroot . '/';
                 unset($SESSION->wantsurl);
             }
         }
         // We do not want to redirect if we are in a PHPUnit test.
         if (!PHPUNIT_TEST) {
             redirect($urltogo);
         }
     }
     // Should never reach here.
     return false;
 }
Ejemplo n.º 25
0
 function loginpage_hook()
 {
     global $CFG, $SESSION, $DB, $USER;
     require_once $CFG->dirroot . '/auth/vatsim/config.php';
     // initiate the SSO class with consumer details and encryption details
     $SSO = new SSO($sso['base'], $sso['key'], $sso['secret'], $sso['method'], $sso['cert']);
     // return variable is needed later in this script
     $sso_return = $sso['return'];
     // remove other config variables
     unset($sso);
     // if VATSIM has redirected the member back
     if (isset($_GET['oauth_verifier']) && !isset($_GET['oauth_cancel'])) {
         // check to make sure there is a saved token for this user
         if (isset($_SESSION[SSO_SESSION]) && isset($_SESSION[SSO_SESSION]['key']) && isset($_SESSION[SSO_SESSION]['secret'])) {
             if (@$_GET['oauth_token'] != $_SESSION[SSO_SESSION]['key']) {
                 throw new moodle_exception("An error occurred with the login process - please try again", 'auth_vatsim');
             }
             if (@(!isset($_GET['oauth_verifier']))) {
                 throw new moodle_exception("An error occurred with the login process", 'auth_vatsim');
             }
             // obtain the details of this user from VATSIM
             $vatsimUser = $SSO->checkLogin($_SESSION[SSO_SESSION]['key'], $_SESSION[SSO_SESSION]['secret'], @$_GET['oauth_verifier']);
             if ($vatsimUser) {
                 // One-time use of tokens, token no longer valid
                 unset($_SESSION[SSO_SESSION]);
                 $vatsim = $vatsimUser->user;
                 //print_r($user->user);
                 $username = $vatsim->id;
                 // plugin only designed where email address is returned, if no email specified,
                 if (@empty($vatsim->email)) {
                     throw new moodle_exception('noemail', "auth_vatsim");
                 }
                 $useremail = $vatsim->email;
                 // find the user in the current database, by CID, not email
                 $user = $DB->get_record('user', array('username' => $username, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id));
                 // create the user if it doesn't exist
                 if (empty($user)) {
                     // deny login if setting "Prevent account creation when authenticating" is on
                     if ($CFG->authpreventaccountcreation) {
                         throw new moodle_exception("noaccountyet", "auth_vatsim");
                     }
                     //retrieve more information from the provider
                     $newuser = new stdClass();
                     $newuser->email = $useremail;
                     $newuser->firstname = $vatsim->name_first;
                     $newuser->lastname = $vatsim->name_last;
                     $newuser->country = $vatsim->country->code;
                     create_user_record($username, '', 'vatsim');
                 } else {
                     $username = $user->username;
                 }
                 add_to_log(SITEID, 'auth_vatsim', '', '', $username . '/' . $useremail);
                 $user = authenticate_user_login($username, null);
                 if ($user) {
                     //prefill more user information if new user
                     if (!empty($newuser)) {
                         $newuser->id = $user->id;
                         $DB->update_record('user', $newuser);
                         $user = (object) array_merge((array) $user, (array) $newuser);
                     }
                     complete_user_login($user);
                     // Redirection
                     if (user_not_fully_set_up($USER)) {
                         $urltogo = $CFG->wwwroot . '/user/edit.php';
                         // We don't delete $SESSION->wantsurl yet, so we get there later
                     } else {
                         if (isset($SESSION->wantsurl) and strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) {
                             $urltogo = $SESSION->wantsurl;
                             // Because it's an address in this site
                             unset($SESSION->wantsurl);
                         } else {
                             // No wantsurl stored or external - go to homepage
                             $urltogo = $CFG->wwwroot . '/';
                             unset($SESSION->wantsurl);
                         }
                     }
                     redirect($urltogo);
                 }
             } else {
                 // OAuth or cURL errors have occurred
                 //$error = $SSO->error();
                 throw new moodle_exception("An error occurred with the login process", 'auth_vatsim');
             }
         }
         // the user cancelled their login and were sent back
     } else {
         if (isset($_GET['oauth_cancel'])) {
             throw new moodle_exception("You cancelled your login", 'auth_vatsim');
         }
     }
     // create a request token for this login. Provides return URL and suspended/inactive settings
     $token = $SSO->requestToken($sso_return, false, false);
     if ($token) {
         // store the token information in the session so that we can retrieve it when the user returns
         $_SESSION[SSO_SESSION] = array('key' => (string) $token->token->oauth_token, 'secret' => (string) $token->token->oauth_token_secret);
         // redirect the member to VATSIM
         $SSO->sendToVatsim();
     } else {
         throw new moodle_exception("An error occurred with the login process", 'auth_vatsim');
     }
 }
Ejemplo n.º 26
0
    }
    $courseid = required_param('courseid', PARAM_INT);
    $session = $DB->get_record_sql('SELECT s.id,c.fullname FROM {user} u INNER JOIN {user_enrolments} ue ON (ue.userid = u.id) INNER JOIN {enrol} e ON (e.id = ue.enrolid) INNER JOIN {course} c ON (e.courseid = c.id) INNER JOIN {local_attendance_session} s ON (c.id=s.courseid) WHERE ue.userid = ' . $user->id . ' AND s.open=1 AND c.id=' . $courseid);
    $attendanceExists = $DB->record_exists("local_attendance_attendance", array('sessionid' => $session->id, 'userid' => $user->id));
    if (!$attendanceExists) {
        $DB->insert_record('local_attendance_attendance', array('sessionid' => $session->id, 'userid' => $user->id, 'ip' => $ip));
    } else {
        echo get_string('alreadyregistered', 'local_attendance');
    }
}
if ($action == "teacherLogin") {
    $username = required_param('user', PARAM_ALPHANUMEXT);
    $password = required_param('pass', PARAM_RAW_TRIMMED);
    if (!($username && $password)) {
        echo get_string('allfields', 'local_attendance');
    } elseif (!($user = authenticate_user_login($username, $password))) {
        echo get_string('invalidlogin', 'local_attendance');
    } else {
        $userCourses = enrol_get_users_courses($user->id);
        $n = 0;
        foreach ($userCourses as $course) {
            $courseContext = context_course::instance($course->id);
            if (has_capability('local/attendance:teacherview', $courseContext, $user->id)) {
                $n++;
            }
        }
        if ($n > 0) {
            $_SESSION['teacher_webapp'] = $user;
        } else {
            echo 'No eres profesor de ningun ramo';
        }
Ejemplo n.º 27
0
 /**
  * Authentication hook - is called every time user hit the login page
  * The code is run only if the param code is mentionned.
  */
 function loginpage_hook()
 {
     global $SESSION, $CFG, $DB, $USER;
     $authorizationcode = optional_param('code', '', PARAM_TEXT);
     if (!empty($authorizationcode) && 200 == $authorizationcode) {
         require_once $CFG->dirroot . '/auth/oauth_simple/lib.php';
         $cfg = get_config('auth/oauth_simple');
         $accesstoken = $SESSION->access_token;
         $connection = new TwitterOAuth($cfg->apiurl, $cfg->baseurl, $cfg->consumer_key, $cfg->consumer_secret, $accesstoken['oauth_token'], $accesstoken['oauth_token_secret']);
         $userinfo = $connection->post($cfg->apifunc);
         if (!empty($userinfo->{$cfg->username})) {
             $user = $DB->get_record('user', array('username' => $userinfo->{$cfg->username}, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id));
             // Create the user if it doesn't exist.
             if (empty($user)) {
                 // Deny login if setting "Prevent account creation when authenticating" is on.
                 if ($CFG->authpreventaccountcreation) {
                     throw new moodle_exception("noaccountyet", "auth_oauth_simple");
                 }
                 $username = $userinfo->{$cfg->username};
                 create_user_record($username, '', 'oauth_simple');
             } else {
                 $username = $user->username;
             }
             // Authenticate the user.
             $userid = empty($user) ? 'new user' : $user->id;
             add_to_log(SITEID, 'auth_oauth_simple', '', '', $username . '/' . $userid);
             $user = authenticate_user_login($username, null);
             if ($user) {
                 // if (!empty($newuser)) {
                 // $newuser->id = $user->id;
                 // $newuser->id = $user->id;
                 // $DB->update_record('user', $newuser);
                 $DB->update_record('user', $user);
                 // $user = (object) array_merge((array) $user, (array) $newuser);
                 // }
                 complete_user_login($user);
                 // Create event for authenticated user.
                 $event = \auth_oauth_simple\event\user_loggedin::create(array('context' => context_system::instance(), 'objectid' => $user->id, 'relateduserid' => $user->id, 'other' => array('accesstoken' => $accesstoken)));
                 $event->trigger();
                 // Redirection.
                 if (user_not_fully_set_up($USER)) {
                     $urltogo = $CFG->wwwroot . '/user/edit.php';
                     // We don't delete $SESSION->wantsurl yet, so we get there later.
                 } else {
                     if (isset($SESSION->wantsurl) and strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) {
                         $urltogo = $SESSION->wantsurl;
                         // Because it's an address in this site.
                         unset($SESSION->wantsurl);
                     } else {
                         // No wantsurl stored or external - go to homepage.
                         $urltogo = $CFG->wwwroot . '/';
                         unset($SESSION->wantsurl);
                     }
                 }
                 redirect($urltogo);
             }
         } else {
             throw new moodle_exception('invalid access', 'auth_oauth_simple');
         }
     }
 }
Ejemplo n.º 28
0
 /**
  * Handle a login event.
  *
  * @param string $oidcuniqid A unique identifier for the user.
  * @param array $authparams Parameters receieved from the auth request.
  * @param array $tokenparams Parameters received from the token request.
  * @param \auth_oidc\jwt $idtoken A JWT object representing the received id_token.
  */
 protected function handlelogin($oidcuniqid, $authparams, $tokenparams, $idtoken)
 {
     global $DB, $CFG;
     $tokenrec = $DB->get_record('auth_oidc_token', ['oidcuniqid' => $oidcuniqid]);
     if (!empty($tokenrec)) {
         $username = $tokenrec->username;
         $this->updatetoken($tokenrec->id, $authparams, $tokenparams);
     } else {
         // Use 'upn' if available for username (Azure-specific), or fall back to lower-case oidcuniqid.
         $username = $idtoken->claim('upn');
         if (empty($username)) {
             $username = strtolower($oidcuniqid);
         }
         $matchedwith = $this->check_for_matched($username);
         if (!empty($matchedwith)) {
             $matchedwith->aadupn = $username;
             throw new \moodle_exception('errorusermatched', 'local_o365', null, $matchedwith);
         }
         $tokenrec = $this->createtoken($oidcuniqid, $username, $authparams, $tokenparams, $idtoken);
     }
     $existinguserparams = ['username' => $username, 'mnethostid' => $CFG->mnet_localhost_id];
     if ($DB->record_exists('user', $existinguserparams) !== true) {
         // User does not exist. Create user if site allows, otherwise fail.
         if (empty($CFG->authpreventaccountcreation)) {
             $user = create_user_record($username, null, 'oidc');
         } else {
             // Trigger login failed event.
             $failurereason = AUTH_LOGIN_NOUSER;
             $eventdata = ['other' => ['username' => $username, 'reason' => $failurereason]];
             $event = \core\event\user_login_failed::create($eventdata);
             $event->trigger();
             throw new \moodle_exception('errorauthloginfailednouser', 'auth_oidc');
         }
     }
     $user = authenticate_user_login($username, null, true);
     if (empty($user)) {
         throw new \moodle_exception('errorauthloginfailednouser', 'auth_oidc');
     }
     complete_user_login($user);
     return true;
 }
Ejemplo n.º 29
-1
     if ($frm->username !== clean_param($frm->username, PARAM_USERNAME)) {
         $errormsg = get_string('username') . ': ' . get_string("invalidusername");
         $errorcode = 2;
         $user = null;
     }
 }
 if ($user) {
     //user already supplied by aut plugin prelogin hook
 } else {
     if ($frm->username == 'guest' and empty($CFG->guestloginbutton)) {
         $user = false;
         /// Can't log in as guest if guest button is disabled
         $frm = false;
     } else {
         if (empty($errormsg)) {
             $user = authenticate_user_login($frm->username, $frm->password, false, $errorcode);
         }
     }
 }
 // Intercept 'restored' users to provide them with info & reset password
 if (!$user and $frm and is_restored_user($frm->username)) {
     $PAGE->set_title(get_string('restoredaccount'));
     $PAGE->set_heading($site->fullname);
     echo $OUTPUT->header();
     echo $OUTPUT->heading(get_string('restoredaccount'));
     echo $OUTPUT->box(get_string('restoredaccountinfo'), 'generalbox boxaligncenter');
     require_once 'restored_password_form.php';
     // Use our "supplanter" login_forgot_password_form. MDL-20846
     $form = new login_forgot_password_form('forgot_password.php', array('username' => $frm->username));
     $form->display();
     echo $OUTPUT->footer();
Ejemplo n.º 30
-1
     if ($frm->username !== clean_param($frm->username, PARAM_USERNAME)) {
         $errormsg = get_string('username') . ': ' . get_string("invalidusername");
         $errorcode = 2;
         $user = null;
     }
 }
 if ($user) {
     //user already supplied by aut plugin prelogin hook
 } else {
     if ($frm->username == 'guest' and empty($CFG->guestloginbutton)) {
         $user = false;
         /// Can't log in as guest if guest button is disabled
         $frm = false;
     } else {
         if (empty($errormsg)) {
             $user = authenticate_user_login($frm->username, $frm->password);
         }
     }
 }
 // Intercept 'restored' users to provide them with info & reset password
 if (!$user and $frm and is_restored_user($frm->username)) {
     $PAGE->set_title(get_string('restoredaccount'));
     $PAGE->set_heading($site->fullname);
     echo $OUTPUT->header();
     echo $OUTPUT->heading(get_string('restoredaccount'));
     echo $OUTPUT->box(get_string('restoredaccountinfo'), 'generalbox boxaligncenter');
     require_once 'restored_password_form.php';
     // Use our "supplanter" login_forgot_password_form. MDL-20846
     $form = new login_forgot_password_form('forgot_password.php', array('username' => $frm->username));
     $form->display();
     echo $OUTPUT->footer();