$key, "status" => 1)); return $user->sid ? $user->sid : ''; } function sess_write($key, $value) { global $HTTP_SERVER_VARS; db_query("UPDATE users SET hostname = '%s', session = '%s', timestamp = '%s' WHERE sid = '$key'", $HTTP_SERVER_VARS["REMOTE_ADDR"], $value, time()); return ''; } function sess_destroy($key) { global $HTTP_SERVER_VARS; db_query("UPDATE users SET hostname = '%s', timestamp = '%s', sid = '' WHERE sid = '$key'", $HTTP_SERVER_VARS["REMOTE_ADDR"], time()); } function sess_gc($lifetime) { return 1; } /*** Common functions ******************************************************/ function user_external_load($authname) { $arr_uid = db_query("SELECT uid FROM authmap WHERE authname = '$authname'"); if (db_fetch_object($arr_uid)) { $uid = db_result($arr_uid); return user_load(array("uid" => $uid)); } else { return 0; } } function user_load($array = array()) { /* ** Dynamically compose a SQL query: */ $query = ""; foreach ($array as $key => $value) { if ($key == "pass") { $query .= "u.$key = '". md5($value) ."' AND "; } else { $query .= "u.$key = '". addslashes($value) ."' AND "; } } $result = db_query("SELECT u.*, r.name AS role FROM users u LEFT JOIN role r ON u.rid = r.rid WHERE $query u.status < 3 LIMIT 1"); $user = db_fetch_object($result); if ($data = unserialize($user->data)) { foreach ($data as $key => $value) { if (!isset($user->$key)) { $user->$key = $value; } } } return $user; } function user_save($account, $array = array()) { /* ** Dynamically compose a SQL query: */ if ($account->uid) { $data = unserialize(db_result(db_query("SELECT data FROM users WHERE uid = '$account->uid'"))); foreach ($array as $key => $value) { if ($key == "pass") { $query .= "$key = '". md5($value) ."', "; } else if (substr($key, 0, 4) !== "auth") { if (in_array($key, user_fields())) { $query .= "$key = '". check_query($value) ."', "; } else { $data[$key] = $value; } } } $query .= "data = '". check_query(serialize($data)) ."', "; db_query("UPDATE users SET $query timestamp = '%s' WHERE uid = '$account->uid'", time()); $user = user_load(array("uid" => $account->uid)); } else { $array["timestamp"] = time(); foreach ($array as $key => $value) { if ($key == "pass") { $fields[] = check_query($key); $values[] = "'". md5($value) ."'"; } else if (substr($key, 0, 4) !== "auth") { if (in_array($key, user_fields())) { $fields[] = check_query($key); $values[] = "'". check_query($value) ."'"; } else { $data[$key] = $value; } } } $fields[] = "data"; $values[] = "'". serialize($data) ."'"; db_query("INSERT INTO users (". implode(", ", $fields) .") VALUES (". implode(", ", $values) .")"); $user = user_load(array("name" => $array["name"])); } foreach ($array as $key => $value) { if (substr($key, 0, 4) == "auth") { $authmaps[$key] = $value; } } if ($authmaps) { $result = user_set_authmaps($user, $authmaps); } return $user; } function user_set($account, $key, $value) { $account->data[$key] = $value; return $account; } function user_get($account, $key) { return $account->data[$key]; } function user_validate_name($name) { /* ** Verify the syntax of the given name: */ if (!$name) return t("You must enter a Username."); if (ereg("^ ", $name)) return t("The Username cannot begin with a space."); if (ereg(" \$", $name)) return t("The Username cannot end with a space."); if (ereg(" ", $name)) return t("The Username cannot contain multiple spaces in a row."); // if (ereg("[^a-zA-Z0-9@-@]", $name)) return t("The Username contains an illegal character."); if (ereg('@', $name) && !eregi('@([0-9a-z](-?[0-9a-z])*\.)+[a-z]{2}([zmuvtg]|fo|me)?$', $name)) return t("The Username is not a valid authentication ID."); if (!eregi('^[[:print:]]+', $name)) return t("The name contains an illegal character."); if (strlen($name) > 56) return t("The Username '$name' is too long: it must be less than 56 characters."); } function user_validate_mail($mail) { /* ** Verify the syntax of the given e-mail address. Empty e-mail addresses ** allowed. */ if ($mail && !eregi("^[_+\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3}$", $mail)) { return t("The e-mail address '$mail' is not valid."); } } function user_validate_authmap($account, $authname, $module) { $result = db_query("SELECT COUNT(*) from authmap WHERE uid != '$account->uid' && authname = '$authname'"); if (db_result($result) > 0) { $name = module_invoke($module, "info", "name"); return t("The %u ID %s is already taken.", array("%u" => ucfirst($name), "%s" => "$authname")); } } function user_password($min_length = 6) { /* ** Generate a human-readable password: */ mt_srand((double)microtime() * 1000000); $words = explode(",", variable_get("user_password", "foo,bar,guy,neo,tux,moo,sun,asm,dot,god,axe,geek,nerd,fish,hack,star,mice,warp,moon,hero,cola,girl,fish,java,perl,boss,dark,sith,jedi,drop,mojo")); while (strlen($password) < $min_length) $password .= trim($words[mt_rand(0, count($words))]); return $password; } function user_access($string) { global $user; static $perm; /* ** To reduce the number of SQL queries, we cache the user's permissions ** in a static variable. */ if (!$perm) { if ($user->uid) { $perm = db_result(db_query("SELECT p.perm FROM role r, permission p WHERE r.rid = p.rid AND name = '$user->role'"), 0); } else { $perm = db_result(db_query("SELECT p.perm FROM role r, permission p WHERE r.rid = p.rid AND name = 'anonymous user'"), 0); } } if ($user->uid == 1) { return 1; } else { return strstr($perm, $string); } } function user_mail($mail, $subject, $message, $header) { if (variable_get("smtp_library", "") && file_exists(variable_get("smtp_library", ""))) { include_once variable_get("smtp_library", ""); return user_mail_wrapper($mail, $subject, $message, $header); } else { return mail($mail, $subject, $message, $header); } } function user_deny($type, $mask) { $allow = db_fetch_object(db_query("SELECT * FROM access WHERE status = '1' AND type = '$type' AND LOWER('$mask') LIKE LOWER(mask)")); $deny = db_fetch_object(db_query("SELECT * FROM access WHERE status = '0' AND type = '$type' AND LOWER('$mask') LIKE LOWER(mask)")); if ($deny && !$allow) { return 1; } else { return 0; } } function user_fields() { static $fields; if (!$fields) { // is this ANSI? perhaps this should go in the database include... $result = db_query("SHOW FIELDS FROM users"); while ($data = db_fetch_object($result)) { $fields[] = $data->Field; } } return $fields; } /*** Module hooks **********************************************************/ function user_perm() { return array("administer users"); } function user_search($keys) { global $PHP_SELF; $result = db_query("SELECT * FROM users WHERE name LIKE '%$keys%' LIMIT 20"); while ($account = db_fetch_object($result)) { $find[$i++] = array("title" => $account->name, "link" => (strstr($PHP_SELF, "admin.php") ? drupal_url(array("mod" => "user", "op" => "edit", "id" => $account->uid), "admin") : drupal_url(array("mod" => "user", "op" => "view", "id" => $account->uid), "module")), "user" => $account->name); } return $find; } function user_block() { global $user, $edit; if ($user->uid) { // Display account settings: $block[0]["subject"] = $user->name; $output = "
". check_output($error) ."
"; } /* ** Save the referer. We record where the user came from such that we ** can redirect him after having completed the login form. */ if (!$edit["destination"]) { $edit["destination"] = request_uri(); } $output .= form_hidden("destination", $edit["destination"]); /* ** Display login form: */ if ($msg) { $output .= "$msg
"; } $output .= form_textfield(t("Username"), "name", $edit["name"], 20, 64, t("Enter your %s username, or an ID from one of our affiliates: %a.", array("%s" => variable_get("site_name", "local"), "%a" => implode(", ", user_auth_help_links())))); $output .= form_password(t("Password"), "pass", $pass, 20, 64, t("Enter the password that accompanies your username.")); $output .= form_checkbox(t("Remember me"), "remember_me", 1, 0, 0); $output .= form_submit(t("Log in")); $output .= "» ". lm(t("E-mail new password"), array("mod" => "user", "op" => "password")). "
";
if (variable_get("user_register", 1)) {
$output .= "» ". lm(t("Create new account"), array("mod" => "user", "op" => "register"));
}
$output .= "
". check_output($error) ."
"; } /* ** Display form: */ $output .= "". sprintf(t("Enter your username %sor%s your e-mail address."), "", "") ."
"; $output .= form_textfield(t("Username"), "name", $edit["name"], 30, 64); $output .= form_textfield(t("E-mail address"), "mail", $edit["mail"], 30, 64); $output .= form_submit(t("E-mail new password")); $output .= "» ". lm(t("Log in"), array("mod" =>user, "op" => "login")) ."
";
if (variable_get("user_register", 1)) {
$output .= "» ". lm(t("Create new account"), array("mod" => "user", "op" => "register"));
}
$output .= "
Welcome to Drupal. You are user #1, which gives you full and immediate access. All future registrants will receive their passwords via e-mail, so please configure your e-mail settings using the Administration pages.
Your password is $pass. You may change your password on the next page.
Please login below.
"; $output .= form_hidden("name", $account->name); $output .= form_hidden("pass", $pass); $output .= form_submit(t("Log in")); return form($output); } else { if ($account->status) { /* ** Create new user account, no administrator approval required: */ $subject = strtr(variable_get("user_mail_welcome_subject", t("User account details for %username at %site")), $variables); $body = strtr(variable_get("user_mail_welcome_body", t("%username,\n\nThank you for registering at %site. You may now login to %uri". drupal_url(array("mod" => "user", "op" => "login"), "module") ." using the following username and password:\n\nusername: %username\npassword: %password\n\nAfter logging in, you may wish to change your password at %urimodule.php?mod=user&op=edit\n\nYour new %site membership also enables to you to login to other Drupal powered websites (e.g. http://www.drop.org/) without registering. Just use the following Drupal ID and password:\n\nDrupal ID: %username@%uri_brief\npassword: %password\n\n\n-- %site team")), $variables); user_mail($edit["mail"], $subject, $body, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from"); return t("Your password and further instructions have been sent to your e-mail address."); } else { /* ** Create new user account, administrator approval required: */ $subject = strtr(variable_get("user_mail_welcome_subject", t("User account details for %username at %site")), $variables); $body = strtr(variable_get("user_mail_welcome_body", t("%username,\n\nThank you for registering at %site. Your account will have to be approved by the site administrator. You may now login to %uri". drupal_url(array("mod" => "user", "op" => "login"), "module") ." using the following username and password:\n\nusername: %username\npassword: %password\n\nAfter logging in, you may wish to change your password at %urimodule.php?mod=user&op=edit\n\nYour new %site membership also enables to you to login to other Drupal powered websites (e.g. http://www.drop.org/) without registering. Just use the following Drupal ID and password:\n\nDrupal ID: %username@%uri_brief\npassword: %password\n\n\n-- %site team")), $variables); user_mail($edit["mail"], $subject, $body, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from"); user_mail(variable_get("site_mail", ini_get("sendmail_from")), $subject, t("%u has applied for an account.\n\n%uri", array("%u" => $account->name, "%uri" => path_uri() . drupal_url(array("mod" => "user", "op" => "edit", "id" => $account->uid), "admin"))), "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from"); return t("Your password and further instructions have been sent to your e-mail address."); } } } else { if ($error) { $output .= "". check_output($error) ."
"; } } // display the registration form $affiliates = user_auth_help_links(); if (array_count_values($affiliates) > 1) { $affiliates = implode(", ", $affiliates); $output .= "" . t("Note: If you have an account with one of our affiliates (%s), you may ". lm("login now", array("mod" => "user", "op" => "login")) ." instead of registering.", array("%s" => $affiliates)) ."
"; } $output .= form_textfield(t("Username"), "name", $edit["name"], 30, 64, t("Your full name or your prefered username: only letters, numbers and spaces are allowed.")); $output .= form_textfield(t("E-mail address"), "mail", $edit["mail"], 30, 64, t("A password and instructions will be sent to this e-mail address, so make sure it is accurate.")); foreach (module_list() as $module) { if (module_hook($module, "user")) { $output .= module_invoke($module, "user", "register_form", $edit, $user); } } $output .= form_submit(t("Create new account")); $output .= "» ". lm(t("E-mail new password"), array("mod" => "user", "op" => "password")). "
";
$output .= "» " .lm(t("Log in"), array("mod" => "user", "op" => "login")). "
". check_output($error) ."
"; } if (!$edit) { $edit = object2array($user); } $output .= form_textfield(t("Username"), "name", $edit["name"], 30, 55, t("Your full name or your prefered username: only letters, numbers and spaces are allowed.")); $output .= form_textfield(t("E-mail address"), "mail", $edit["mail"], 30, 55, t("Insert a valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.")); foreach (module_list() as $module) { if (module_hook($module, "user")) { $output .= module_invoke($module, "user", "edit_form", $edit, $user); } } $output .= form_textfield(t("Homepage"), "homepage", $edit["homepage"], 30, 55, t("Optional") .". ". t("Make sure you enter a fully qualified URL: remember to include \"http://\".")); foreach (theme_list() as $key => $value) { $options .= "$value[type]\n"; } $output .= form_item(t("Theme"), "", t("Selecting a different theme will change the look and feel of the site.")); for ($zone = -43200; $zone <= 46800; $zone += 3600) $zones[$zone] = date("l, F dS, Y - h:i A", time() - date("Z") + $zone) ." (GMT ". $zone / 3600 .")"; $output .= form_select(t("Timezone"), "timezone", $edit["timezone"], $zones, t("Select what time you currently have and your timezone settings will be set appropriate.")); $output .= form_select(t("Language"), "language", $edit["language"], $languages, t("Selecting a different language will change the language of the site.")); $output .= form_textarea(t("Signature"), "signature", $edit["signature"], 70, 3, t("Your signature will be publicly displayed at the end of your comments.") ."". check_output($error) ."
"; } $output .= form_textfield("Username", "name", $edit["name"], 30, 55); $output .= form_textfield("E-mail address", "mail", $edit["mail"], 30, 55); $output .= form_textfield("Password", "pass", $edit["pass"], 30, 55); $output .= form_submit("Create account"); return form($output); } } function user_admin_access($edit = array()) { global $op, $id, $type; $output .= "". la(t("e-mail rules"), array("mod" => "user", "op" => "access", "type" => "mail")) ." :: ". la(t("username rules"), array("mod" => "user", "op" => "access", "type" => "user")) ."type | mask | operations |
---|---|---|
allow | ". check_output($rule->mask) ." | ". la(t("delete rule"), array("mod" => "user", "op" => "access", "type" => $type, "id" => $rule->aid)) ." |
deny | ". check_output($rule->mask) ." | ". la(t("delete rule"), array("mod" => "user", "op" => "access", "type" => $type, "id" => $rule->aid)). " |
%: matches any number of characters, even zero characters.
_: matches exactly one character.
". implode(" | ", array_values($role_names)) ." | |
---|---|---|
". check_output($perm) ." | "; foreach ($role_names as $rid => $name) { $output .= ""; } $output .= " |
name | operations |
---|---|
". check_output($role->name) ." | ". la(t("edit role"), array("mod" => "user", "op" => "role", "id" => $role->rid)) ." |
". check_output($error) ."
"; } } else if ($op == "Delete account") { if ($edit["status"] == 0) { db_query("DELETE FROM users WHERE uid = '$account->uid'"); db_query("DELETE FROM authmap WHERE uid = '$account->uid'"); $output .= t("The account has been deleted."); } else { $output .= t("Failed to delete account: the account has to be blocked first."); } } /* ** Display user form: */ $output .= form_item("User ID", check_output($account->uid)); $output .= form_textfield(t("Username"), "name", $account->name, 30, 55, t("Your full name or your prefered username: only letters, numbers and spaces are allowed.")); $output .= form_textfield(t("E-mail address"), "mail", $account->mail, 30, 55, t("Insert a valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.")); foreach (module_list() as $module) { if (module_hook($module, "user")) { $output .= module_invoke($module, "user", "edit_form", $edit, $account); } } $output .= form_textfield(t("Homepage"), "homepage", $account->homepage, 30, 55, t("Optional") .". ". t("Make sure you enter a fully qualified URL: remember to include \"http://\".")); foreach (theme_list() as $key => $value) { $options .= "$value[type]\n"; } $output .= form_item(t("Theme"), "", t("Selecting a different theme will change the look and feel of the site.")); for ($zone = -43200; $zone <= 46800; $zone += 3600) $zones[$zone] = date("l, F dS, Y - h:i A", time() - date("Z") + $zone) ." (GMT ". $zone / 3600 .")"; $output .= form_select(t("Timezone"), "timezone", $account->timezone, $zones, t("Select what time you currently have and your timezone settings will be set appropriate.")); $output .= form_select(t("Language"), "language", $account->language, $languages, t("Selecting a different language will change the language of the site.")); $output .= form_textarea(t("Signature"), "signature", $account->signature, 70, 3, t("Your signature will be publicly displayed at the end of your comments.") ."username | last access | operations |
---|---|---|
". format_name($account) ." | ". format_date($account->timestamp, "small") ." | ". la(t("edit account"), array("mod" => "user", "op" => "edit", "id" => $account->uid)) ." |
One of the more tedious moments in visiting a new website is filling out the registration form. Here at %s, you do not have to fill out a registration form if you are already a member of "; $output .= implode(", ", user_auth_help_links()); $output .= ". This capability is called Distributed Authentication, and is unique to Drupal, the software which powers %s.
Distributed Authentication enables a new user to input a username and password into the login box, and immediately be recognized, even if that user never registered at %s. This works because Drupal knows how to communicate with external registration databases. For example, lets say that new user 'Joe' is already a registered member of Delphi Forums. Drupal informs Joe on registration and login screens that he may login with his Delphi ID instead of registering with %s. Joe likes that idea, and logs in with a username of joe@remote.delphiforums.com and his usual Delphi password. Drupal then contacts the remote.delphiforums.com server behind the scenes (usually using XML-RPC, HTTP POST, or SOAP) and asks: \"Is the password for user Joe correct?\". If Delphi replies yes, then we create a new $site account for Joe and log him into it. Joe may keep on logging into %s in the same manner, and he will always be logged into the same account.
"; $output = strtr($output, array("%s" => $site)); foreach (module_list() as $module) { if (module_hook($module, "auth")) { $output .= "Drupal offers a powerful and open user system. This system allows users to register, login, logout, maintain user profiles, etc. No participant can use his own name to post comments until he signs up and submits his e-mail address. Those who do not register may participate as anonymous users, but they will suffer numerous disadvantages, for example their posts beginning at a lower score.
In contrast, those with a user account can use their own name or handle and are granted various privileges: the most important are probably the ability to moderate new submissions, to rate comments, and to fine-tune the site to their personal liking. Drupal themes make fine tuning quite a pleasure.
Registered users need to authenticate by supplying a username and password. Users may authenticate locally or via an external authentication source like Jabber, Delphi, and other Drupal websites. See Distributed Authentication for more information on this innovative feature. The username and password are kept in your database, where the password is hashed so that no one can read nor use it. When a username and password needs to be checked the system goes down the list of registered users until it finds a matching username, and then hashes the password that was supplied and compares it to the listed value. If the hashes match, the username and password are correct. Once a user authenticated session is started, and until that session is over, the user won't have to re-authenticate. To keep track of the individual sessions, Drupal relies on PHP's session support. A visitor accessing your website is assigned an unique ID, the so-called session ID, which is stored in a cookie. For security's sake, the cookie does not contain personal information but acts as a key to retrieve the information stored on your server's side. When a visitor accesses your site, Drupal will check whether a specific session ID has been sent with the request. If this is the case, the prior saved environment is recreated.
Authenticated users can select entirely different appearances for the site,
utilizing their own preferences for how the pages are structured, how navigation
lists and other page components are presented and much more.
Administrators manage user accounts by clicking on the User management link in their Admin interface. There, you will find several configuration pages and reports which help you manage your users. The following pages are available:
If your site is completely private, and doesn't allow registration for any old web user (see settings for this feature), then you'll need to add new users manually. This web page allows any administrator to register a new user.
Access rules enable administrators to filter out usernames and e-mail addresses which are not allowed in Drupal. An administrator creates a 'mask' against which each new registration is checked. Disallowed names and e-mail addresses are denied access to the site. Another handy use for this page is to disallow registration to your site from an untrusted external authentication server. Just add their server address to the username mask section and you've effectively blocked all logins from that server.
To do describe access rules you can use the following wild-card characters:
Examples:
%@hotmail.com
, %@altavista.%
, %@usa.net
, etc. Used to prevent users from using free e-mail accounts, which might be used to cause trouble.root
, webmaster
, admin%
, etc. Used to prevent administrator impersonators.If no access rules are provided, access control is turned off and everybody will be able to access your website. The 'allow' rules are processed prior to the 'deny' rules and are thus considered to be stronger.
This page is quite powerful. It allows an administrator to review any user's profile. In addition, administrators may block any user, or assign him a role, using this page.
Roles allow you to fine tune the security and administration of drupal. A role defines a group of users which have certain privileges. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. By default, Drupal comes with two commonly used roles:
These common roles will suffice for most sites. However, for a more complex site where you need to give several users different access privileges, you will need to add a new role by clicking the "add new role" link. Then define what privileges that role will have by clicking the "permission overview" link and checking the appropriate boxes to give that role the permissions you desire.
To attach a specific user to a role, use the "account" section of the drupal Administration.
Note: If you intend for a user to access certain sections of the administration pages, they must have "access administration page" privileges.
Each role has certain things that its users are allowed to do, and some that are disallowed. For example, authenticated users may usually post a story but Anonymous users may not.
Each permission describes a fine-grained logical operation such as access administration pages or add and modify user accounts. You could say a permission represents access granted to a user to perform a set of operations.
Search Account enables an admin to query for any username in the user table and return users which match that query. For example, one may search for 'br' and Drupal might return 'brian', 'brad', and 'brenda'.
Administrators may choose to restrict registration to their site. That restriction may be accomplished on this page. Also, the list of words which may be included in a system generated password is also listed on this page. Drupal generates passwords by joining small words from the password list until the new password is greater than 6 characters.
All users sorted by most recent login.
All users sorted by most recent registration
All users who have been blocked (status = 0) sorted by most recent registration
All roles present a report listing their members
Drupal comes with a set of user preferences and profile which a user may edit by clicking on the user account link. Of course, a user must be logged into reach those pages. There, users will find a page for changing their preferred timezone, language, username, e-mail address, password, theme, signature, homepage, and distributed authentication names. Changes made here take effect immediately. Also, administrators may make profile and preferences changes in the Admin Center on behalf of their users.
Module developers are provided several hooks for adding custom fields to the user view/edit pages. These hooks are described in the Developer section of the Drupal Handbook. For an example, see the jabber_user()
function in /modules/jabber.module.
One of the more tedious moments in visiting a new website is filling out the registration form. The reg form provides helpful information to the website owner, but not much value for the user. The value for the end user is usually a the ability to post a messages or receive personalized news, etc. Distributed authentication (DA) gives the user what he wants without having to fill out the reg form. Removing this obstacle yields more registered and active users for the website.
DA enables a new user to input a username and password into the login box and immediately be recognized, even if that user never registered on your site. This works because Drupal knows how to communicate with external registration databases. For example, lets say that your new user 'Joe' is already a registered member of Delphi Forums. If your Drupal has delphi.module installed, then Drupal will inform Joe on the registration and login screens that he may login with his Delphi ID instead of registering with your Drupal instance. Joe likes that idea, and logs in with a username of joe@remote.delphiforums.com and his usual Delphi password. Drupal then communicates with remote.delphiforums.com (usually using XML-RPC, HTTP POST, or SOAP) behind the scenes and asks "is this password for username=joe? If Delphi replies yes, then Drupal will create a new local account for joe and log joe into it. Joe may keep on logging into your Drupal instance in the same manner, and he will be logged into the same joe@remote.delphiforums.com account.
One key element of DA is the 'authmap' table, which maps a user's authname (e.g. joe@remote.delphiforums.com) to his local UID (i.e. universal identification number). This map is checked whenever a user successfully logs into an external authentication source. Once Drupal knows that the current user is definately joe@remote.delphiforums.com (because Delphi says so), he looks up Joe's UID and logs Joe into that account.
To disable Distributed Authentication, simply disable or remove all DA modules. For a virgin install, that means removing/disabling jabber.module and drupal.module
Drupal is setup so that it is very easy to add support for any external authentication source. You currently have the following authentication modules installed ...
foreach (module_list() as $module) { if (module_hook($module, "auth")) { print "Drupal is specifically architected to enable easy authoring of new authentication modules. I'll deconstruct the Blogger authentication module here, and hopefully provide all the details you'll need to write a new auth module. If you want to download the full text of this module, visit the Drupal-Contrib repository.
<?php
The first line of every authentication module is the same. It is the standard processing instruction for any PHP file. Authentication modules are always written in PHP, although they typically interact with systems written in many different programming languages and operating systems languages.
function blogger_info($field = NULL) { $info["name"] = "Blogger"; $info["protocol"] = "XML-RPC"; $info["link"] = "Blogger"; $info["maintainer"] = "Moshe Weitzman"; $info["maintaineremail"] = "weitzman at tejasa.com"; if ($field) return $info[$field]; else return $info; }
The _info function is always the first function defined in your module. This function populates an array called $info with various pieces of data. Some of this data is used by Drupal ("name", "link"), and some of it just informs the users of your module. Your goal is to simply copy the blogger_info function in your module - but wherever it says blogger here, substitute your own module name.
function blogger_auth($name, $pass, $server) { if ($server !== "blogger.com") return 0; // user did not present a Blogger ID so don't bother trying. $appkey = "6D4A2D6811A6E1F75148DC1155D33C0C958107BC"; //provided to Drupal by Ev@Blogger $message = new xmlrpcmsg("blogger.getUsersBlogs", array(new xmlrpcval($appkey, "string"), new xmlrpcval($name, "string"), new xmlrpcval($pass, "string"))); $client = new xmlrpc_client("/api/RPC2", "plant.blogger.com");
$result = $client->send($message, 5); // since Blogger doesn't return properly formed FaultCode, we just search for the string 'fault' if ($result && !stristr($result->serialize(), "fault")) { // watchdog("user", "Success Blogger Auth. Response: " . $result->serialize()); return 1; } else if ($result) { // watchdog("user", "Blogger Auth failure. Response was " . $result->serialize()); return 0; } else { // watchdog("user", "Blogger Auth failure. Could not connect."); return 0; } }
The _auth function is the heart of any authentication module. This function is called whenever a user is attempting to login using your authentication module. For successful authentications, this function returns TRUE. Otherwise, it returns FALSE. This function always accepts 3 parameters, as shown above. These parameters are passed by the user system (user.module). The user system parses the username as typed by the user into 2 substrings - $name and $server. The parsing rules are:
_auth function parameters
|
|
$name | The substring before the final '@' character in the username field |
$pass | The whole string submitted by the user in the password field |
$server | The substring after the final '@' symbol in the username field |
So now lets use that $name, $pass, and $server which has been passed to our _auth function. Blogger authenticates users via XML-RPC. Your module may authenticate using a different technique. Drupal doesn't reallly care how your module communicates with its registration source. It just trusts the module.
The lines above illustrate a typical XML-RPC method call. Here we build up a message and send it to Blogger, storing the response in a variable called $response. The message we pass conforms to the published Blogger XML-RPC API. Your module will no doubt implement a different API. One peculiarity of this module is that we don't actually use the $server parameter. Blogger only accepts authentication at plant.blogger.com, so we hard-code that value into the xmlrpc_client() function. A more typical example might be the jabber module, which uses the $server parameter to determine where to send the authentication request. Also of note is the '5' parameter in the $client->send() call. This is a timeout value in seconds. All authentication modules should implement a timeout on their external calls. This makes sure to return control to the user.module if your registration database has become inoperable or unreachable.
if ($result && !stristr($result->serialize(), "fault")) { // watchdog("user", "Success Blogger auth. Response was " . $result->serialize()); return 1; } else if ($result) { // watchdog("user", "Blogger auth failure. Response was " . $result->serialize()); return 0; } else { // watchdog("user", "Blogger auth failure. Could not connect.");
return 0; }
This second half of the _auth function examines the $response from plant.blogger.com and returns a TRUE or FALSE as appropriate. This is a critical decision, so do be sure you have good logic here, and perform sufficient testing for all cases. In the case of Blogger, we search for the string 'fault' in the response. If that string is present, or there is no repsonse, our function returns FALSE. Otherwise, Blogger has returned valid data to our method request and we return TRUE. There are several watchdog() calls here which are commented out. These are useful for debugging, so I've left them in the code as comments.
function blogger_page() { global $theme; $theme->header(); $theme->box("Blogger", blogger_auth_help()); $theme->footer(); }
The _page function is not currently used, but it might be in the future. For now, just copy what you see here, substituting your module name for blogger.
function blogger_auth_help() { $site = variable_get("site_name", "this web site"); $html_output = " <p>You may login to <i>%s</i> using a <b>Blogger ID</b> and password. A Blogger ID consists of your Blogger username followed by <i>@blogger.com</i>. So a valid blogger ID is mwlily@blogger.com. If you are a Blogger member, go ahead and login now.</p>
<p>Blogger offers you instant communication power by letting you post your thoughts to the web whenever the urge strikes. Blogger will publish to your current web site or help you create one. <a href=\"http://www.blogger.com/about.pyra\">Learn more about it</a>."; return sprintf(t($html_output), $site); }
The _auth_help function is prominently linked within Drupal, so you'll want to write the best possible user help here. You'll want to tell users what a proper username looks like for your authentication module. Also, you may advertise a bit about your service at the end. Note that your help text is passed through a t() function in the last line. This is Drupal's localization function. Translators may localize your help text just like any other text in Drupal.
Once you've written and tested your authentication module, you'll have to usually
want to share it with the world. The best way to do this is to add the module
to the Drupal-Contrib
repository. You'll need to request priveleges in this repository - see README
for the details. Then you'll want to announce your contribution on the Drupal_devel
and Drupal_support mailing lists. You might also want to post a story on
Drop.org.
The _user() hook provides to Module Authors a mechanism for inserting text and form fields into the registration page, the user account view/edit pages, and the administer users page. This is useful if you want to add a custom field for your particular community. This is best illustrated by an example called profile.module in the Contrib repository. Profile.module is meant to be customized for your needs. Please download it and hack away until it does what you need.
Consider this simpler example from a fictional recipe community web site called Julia's Kitchen. Julia customizes her Drupal powered site by creating a new file called julia.module. That file does the following: - new members must agree to Julia's Privacy Policy on the reg page. - members may list their favorite ingredients on their public user profile page
Julia achieves this with the following code. The comments below should help you understand what is going on.
function julia_user($type, $edit, &$user) { switch ($type) { case "register_form": $output .= form_item("Privacy Policy", "Julia would never sell your user information. She is just nice old French chef who lives near me in Cambridge, Massachussetts USA."); $output .= form_checkbox("Accept Julia's Kitchen privacy policy.", julia_accept, 1, $edit["julia_accept"]); return $output; case "register_validate": if ($edit["julia_accept"] == "1") { // on success return the values you want to store return array("julia_accept" => 1); } else { // on error return an error message return "You must accept the Julia's Kitchen privacy policy to register."; } case "view_public": // when others look at user data return form_item("Favorite Ingredient", $user->julia_favingredient); case "view_private": // when user tries to view his own user page. return form_item("Favorite Ingredient", $user->julia_favingredient); case "edit_form": // when user tries to edit his own user page. return form_textfield("Favorite Ingredient", "julia_favingredient", $user->julia_favingredient, 50, 65, "Tell everyone your secret spice"); case "edit_validate": return user_save($user, array("julia_favingredient" => $edit["julia_favingredient"])); } }
Extra credit: use the hotlist.module to provide Julia users a mechanism for bookmarking their favorite recipes.
} ?>