Auto assign role based on registration code

adfad666 - May 31, 2008 - 00:40

I'm wondering if it's possible to auto assign a role to a new user when they register, based on a registration code they enter.

I'd like to be able to have different groups of people sign up using a different registration code for each group, which then assigns them a role that is matched with that code.

This way I'll be able to embed Gallery2 and set various albums to only show when the role assigned to that album matches the auto assigned role of the user. I've been able to get it to work by assigning the roles manually, so now i just need to get it to work automatically on registration.

Basically I want to be able to do this:

UserA, UserB and UserC sign up using RegCode1 which enables them to see Album1
UserX, UserY and UserZ sign up using RegCode2 which enables them to see Album2
Guests can see neither album, Admins can see all.
neither group should be aware that the other album exists.

Any help will be much appreciated.

Adam

Try auto assign role module

Alan D. - May 31, 2008 - 03:41

While is it not exactly what you want, this module http://drupal.org/project/autoassignrole will guide you in your quest. Should be fairly simple to modify things to check flags to filter the role assignment.

Alan Davison
www.caignwebs.com.au

that's what I thought

adfad666 - June 1, 2008 - 20:49

I had come accross this module in my search, and also one called regcode http://drupal.org/project/regcode, which were the closest things to what I need, but alas I do not have much of an understanding of php or anything like that to combime them. I think now is a good enough time to start learning it I guess...

beginnings

adfad666 - June 4, 2008 - 23:39

well, after studying the database and some of the documentation, I think the best way to do this is to add a new column to the {role} table, which i've called 'key', that stores the unique registration code for the roles.

next I add a textfield to the registration page for users to insert their codes. when they press submit the code is checked against the {roles} table for any matching 'key' fields, and passing back the 'rid' for that role.

finally the determined 'rid' and the new users' 'uid' get added to the {users_roles} table as normal.

after a bit of guesswork I've come up with the snippets of code below. I have no idea if it's anything near to workable, so if anyone can suggest the next step in getting this to work?

<?php

  $form
['regcoderole_code'] = array(
   
'#type' => 'textfield',
   
'#title' => t('Registration Code'),
   
'#value' => $regcoderole_code,
   
'#size' => 32,
   
'#maxlength' => 32,
   
'#required' => TRUE,
   
'#description' => t('Please enter your registration code.')
  ); 
return
$form;

 
$sql1 = "SELECT rid FROM {role} WHERE key = '$regcoderole_code'";
 
$regcoderole_role = db_result(db_rewrite_sql($sql1));

 
$sql2 = 'INSERT INTO {users_roles} (uid, rid) values ($user->uid, $regcoderole_role)';
 
$result = db_query(dbrewrite_sql($sql2));

?>

OK so after playing with the

adfad666 - June 5, 2008 - 08:46

OK so after playing with the regcode module, I've come up with this so far, where it's mainly from the last function with some changes. it loads and displays the 'Registration Code' box on the registration page, but when you submit it, it comes up with the following error:

    * warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/adfad666/public_html/drupal/includes/database.mysql.inc on line 236.

The user is still created as normal, but no extra roles are assigned in the {user_roles} table.

getting closer! can anyone see what needs to be changed?

<?php
// $Id: regcoderole.module,v 0.1 $

/**
* @file
*   regcoderole.module
*/

function regcoderole_perm() {
  return array(
'administer registration codes');
}

function
regcoderole_user($op, &$edit, &$account, $category = NULL) {

 
// Only do the checking if the codes variable is set.
   
switch ($op) {

      case
'register':
       
// Inject the registration code field into the registration form.
       
$form['regcoderole_code'] = array(
         
'#type' => 'textfield',
         
'#title' => t('Registration Code'),
         
'#value' => $regcoderole_code,
         
'#required' => TRUE,
         
'#description' => t('Please enter your registration code.')
        );
        return
$form;

      case
'validate':
        if ((
$category == 'account') && (!$account->uid)) {  
         
// Make sure that the entered code is in the list.
        
          
$sql1 = "SELECT rid FROM {role} WHERE key = '$regcoderole_code'";
          
$regcoderole_role = db_result(db_rewrite_sql($sql1));
                   return
$regcoderole_role;
        
        
$sql2 = 'INSERT INTO {users_roles} (uid, rid) values ($account, $regcoderole_role)';
        
$result = db_query(db_rewrite_sql($sql2));
        
        }
        break;
    }
// switch
}


?>

Some of these posts must

adfad666 - June 5, 2008 - 16:50

Some of these posts must look rediculous to the knowledgable coders out there...

but anyway here's the latest on what i've got. the code is a bit tidier and should make a little bit more sense. it doesn't give errors anymore, but it still doesn't add the fields to the database.

<?php

<?php
// $Id: regcoderole.module,v 0.1 $

/**
* @file
*   regcoderole.module
*/

function regcoderole_perm() {
  return array(
'administer registration codes');
}


function
regcoderole_user($type, &$edit, &$account, $category = NULL) {
    switch (
$type) {
      case
'register':
       
$form['regcoderole_code'] = array(
         
'#type' => 'textfield',
         
'#title' => t('Registration Code'),
         
'#value' => $regcode,
         
'#required' => TRUE,
         
'#description' => t('Please enter your registration code.')
        );
        return
$form;
      case
'validate':        
         if (
$regcode > 0) {
          
$sql = 'SELECT rid FROM {role} WHERE key = (%d)'
          
$result = db_result($sql, $regcode);
             if (
$result > 0) {
              
$sql = 'INSERT INTO {users_roles} (uid, rid) values (%d, %d)'
              
db_query($sql, $account->uid, $result);
            }
         }
        }
}

?>

Is reg code numeric?

Alan D. - June 6, 2008 - 09:26

Without running the code, the only thing that stands out is the the select statement. %d casts the value to an integer, so 'w345' would become '2343245' or something.

The change to this would be db_query("SELECT rid FROM {role} WHERE key = '%s'", $regcode)

Install devel module and use the statement "dpm($result);" to echo the debugging statement to the screen. This one shows as a message after a submit, dpr($var) is a nice var_dump. If FALSE or NULL, both of these statements do not show anything. A var_dump($x); die; is a quick way of seeing whats happening.

If you enable DB logging; "Collect query info" & "Display query log" you can see what is exactly happening to the query. This adds a huge list of sql statements to every page load. Use the browsers find function for some keyword of the query.

Alan Davison
www.caignwebs.com.au

thank's for the tips, i've

adfad666 - June 6, 2008 - 11:36

thank's for the tips, i've changed the suggestions you gave me.

I also enabled the Devel module, and from what I can see, I don't think the sql queries are even being execueted!

take a look at http://c2e.exofire.net/drupal and register an account, I can't see either of my queries in the list...

<?php
// $Id: regcoderole.module,v 0.1 $

/**
* @file
*   regcoderole.module
*/

function regcoderole_perm() {
  return array(
'administer registration codes');
}


function
regcoderole_user($op, &$edit, &$account, $category = NULL) {
    switch (
$op) {
      case
'register':
       
$form['regcoderole_code'] = array(
         
'#type' => 'textfield',
         
'#title' => t('Registration Code'),
         
'#default_value' => $regcode,
         
'#required' => TRUE,
         
'#description' => t('Please enter your registration code.'),
        );
        return
$form;
        break;
      case
'validate':
         if (
$regcode > 0) {
          
$sql = "SELECT * FROM {role} WHERE rolekey = '%s'";
          
$result = db_result($sql, $regcode);
             if (
$result > 0) {
              
$sql = "INSERT INTO {users_roles} (uid, rid) values (%d, %d)";
              
db_query($sql, $account->uid, $result);
            }
         }
        }
}
?>

K, had to read the hook_user api

Alan D. - June 6, 2008 - 11:57

Right, having a look at the hook_user entry in the api's, http://api.drupal.org/api/function/hook_user

Don't use validate, the user has not been created yet, and even if they had, a validation error will return the form and it will not be submitted.

Since we are only interested in new users, use the 'insert' $op, the user should be created, and you will have a valid user object with a real uid.

Without setting up a test myself to play with, check that $edit['regcode'] is set, it may be referenced as $edit['values']['regcode'].

changes would then be:

<?php
....
      case
'insert':
        
dpm('Insert called');
        
dpm($edit);
        
// Is regcode a String "abc" or positive integer?
        
$regcode = trim($edit['regcode']);
        
// If it is a string code
        
if (strlen($regcode)) {
          
dpm($regcode . ' was not empty string');
          
$sql = "SELECT * FROM {role} WHERE rolekey = '%s'";
           if (
$result = db_result($sql, $regcode)) {
              
dpm($regcode . ' matched');
              
$sql = "INSERT INTO {users_roles} (uid, rid) values (%d, %d)";
              
db_query($sql, $account->uid, $result);
            }
         }
         else {
          
dpm($regcode . ' DID NOT EXIST');
         }
      }
....
?>

PS: Disable the debugging statements until you need them. They prevent the submit redirects, and they also cause AJAX errors.

Alan Davison
www.caignwebs.com.au

Ok the code appears to

adfad666 - June 6, 2008 - 12:44

Ok the code appears to work... except it's not using the regcode given in the registration form. I don't have anywhere else within mycode that mentions $edit['regcode'] so i'm not sure where i'd be setting it. I did have a play and changed it to $edit['regcoderole_code'] thinking maybe you meant the form from above it, but that broke it completely.

there's two test roles set with rolekeys 1234567890 and testkey123 if you want to have another look

<?php
// $Id: regcoderole.module,v 0.1 $

/**
* @file
*   regcoderole.module
*/

function regcoderole_perm() {
  return array(
'administer registration codes');
}


function
regcoderole_user($op, &$edit, &$account, $category = NULL) {
    switch (
$op) {
      case
'register':
       
$form['regcoderole_code'] = array(
         
'#type' => 'textfield',
         
'#title' => t('Registration Code'),
         
'#default_value' => $regcode,
         
'#required' => TRUE,
         
'#description' => t('Please enter your registration code.'),
        );
        return
$form;
        break;
      case
'insert':
        
dpm('Insert Called');
        
dpm($edit);
        
// Is regcode a String "abc" or positive integer?
        
$regcode = trim($edit['regcode']);          //is this line right???
         // If it is a string code
        
if (strlen($regcode)) {
          
dpm($regcode . ' was not empty string');
             
$sql = "SELECT * FROM {role} WHERE rolekey = '%s'";
           if (
$result = db_result($sql, $regcode)) {
            
dpm($regcode . ' matched');
              
$sql = "INSERT INTO {users_roles} (uid, rid) values (%d, %d)";
              
db_query($sql, $account->uid, $result);
            }
         }
         else {
          
dpm($regcode . ' DID NOT EXIST');
         }
       }
}
?>

It's been a long week...

Alan D. - June 6, 2008 - 12:52

Yep, that lines wrong, use 'regcoderole_code' instead of 'regcode'

Sorry bout that.

Alan Davison
www.caignwebs.com.au

Security warning about Devel

Alan D. - June 6, 2008 - 12:55

While good for allowing me to test, you should create a role 'developer', and make sure that no-one has access to the Devel except for developers.

This prevents non-developers seeing these messengers, and hides potentially dangerous "switch user" and "execute php" blocks

Cheers

Alan Davison
www.caignwebs.com.au

now it spits me out at

adfad666 - June 6, 2008 - 13:01

now it spits me out at "testkey123 was not empty string" with the error

warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/adfad666/public_html/drupal/includes/database.mysql.inc on line 236.

BTW i'm extremely greatful for you're help so far!

db_result only accepts a single result

Alan D. - June 6, 2008 - 13:09

Change "SELECT * FROM {role} WHERE rolekey = '%s'" to "SELECT rid FROM {role} WHERE rolekey = '%s'"

Yep, long week. lol

Alan Davison
www.caignwebs.com.au

ahh i'm not worried about

adfad666 - June 6, 2008 - 13:11

ahh i'm not worried about security on this at the moment, this is just a freebie test server for figuring all this out so i'm not at all fussed about having to wipe it and starting again!

heck I could just give you an admin account if that'd help if you signed up with a real email address. my actual web server has nothing to do with this...

ok i've changed it to

adfad666 - June 6, 2008 - 13:29

ok i've changed it to %form['regcoderole_code'] from %edit['regcode'] and changed the db_result line from * to rid. this got rid of the error but is still coming up with DID NOT EXIST.

<?php
// $Id: regcoderole.module,v 0.1 $

/**
* @file
*   regcoderole.module
*/

function regcoderole_perm() {
  return array(
'administer registration codes');
}


function
regcoderole_user($op, &$edit, &$account, $category = NULL) {
    switch (
$op) {
      case
'register':
       
$form['regcoderole_code'] = array(
         
'#type' => 'textfield',
         
'#title' => t('Registration Code'),
         
'#default_value' => $regcode,
         
'#required' => TRUE,
         
'#description' => t('Please enter your registration code.'),
        );
        return
$form;
        break;
      case
'insert':
        
dpm('Insert Called');
        
dpm($edit);
        
// Is regcode a String "abc" or positive integer?
        
$regcode = trim($form['regcoderole_code']);
        
// If it is a string code
        
if (strlen($regcode)) {
          
dpm($regcode . ' was not empty string');
             
$sql = "SELECT rid FROM {role} WHERE rolekey = '%s'";
           if (
$result = db_result($sql, $regcode)) {
            
dpm($regcode . ' matched');
              
$sql = "INSERT INTO {users_roles} (uid, rid) values (%d, %d)";
              
db_query($sql, $account->uid, $result);
            }
         }
         else {
          
dpm($regcode . ' DID NOT EXIST');
         }
       }
}
?>

Use $edit not $form

Alan D. - June 6, 2008 - 13:34

Somehow the $edit variable was replaced with $form $regcode = trim($form['regcoderole_code']);

Alan Davison
www.caignwebs.com.au

changing it back to

adfad666 - June 6, 2008 - 13:48

changing it back to %edit['regcoderole_code'] brings back the mySQL error from above, something about an invalid argument resource?

can you dump the sql arguments and sql?

Alan D. - June 6, 2008 - 14:14

try test dpm()'s
dpm($account, 'account'); // is this an array or object
dpm($result, 'result'); // did this return a strange result
dpm("INSERT INTO {users_roles} (uid, rid) values ({$account->uid}, $result)");

It may solve the puzzle. Also change the function case to case '_insert' : and check that something else hasn't broken. It is late on the other side of the world, so I wish you luck on your quest. :)

Alan Davison
www.caignwebs.com.au

Success!!! OK well

adfad666 - June 6, 2008 - 21:40

Success!!! OK well nearly...

I had to change the db_result to a db_query with SELECT * to get it to do anything. Once i'd done that it completed and inserted the uid and rid into the {user_roles} table. However it puts in the wrong rid!!

I've added the three dpm you suggested above, and it turns out that the value you get for the $result is wrong. It calls it "Resource id #143" instead of the value of the rid queried...

the below code is still active on the test site if you want to see the full results for your self:

<?php
// $Id: regcoderole.module,v 0.1 $

/**
* @file
*   regcoderole.module
*/

function regcoderole_perm() {
  return array(
'administer registration codes');
}


function
regcoderole_user($op, &$edit, &$account, $category = NULL) {
    switch (
$op) {
      case
'register':
       
$form['regcoderolecode'] = array(
         
'#type' => 'textfield',
         
'#title' => t('Registration Code'),
         
'#default_value' => $regcode,
         
'#required' => TRUE,
         
'#description' => t('Please enter your registration code.'),
        );
        return
$form;
        break;
      case
'insert':
        
              
              
        
dpm('Insert Called');
        
dpm($edit);
        
// Is regcode a String "abc" or positive integer?
        
$regcode = trim($edit['regcoderolecode']);
        
// If it is a string code
        
if (strlen($regcode)) {
          
dpm($regcode . ' was not empty string');
             
$sql = "SELECT * FROM {role} WHERE rolekey = '%s'";
           if (
$result = db_query($sql, ($regcode->rid))) {
            
dpm($regcode . ' matched');
              
$sql = "INSERT INTO {users_roles} (uid, rid) values (%d, %d)";
              
db_query($sql, $account->uid, $result);
              
              
dpm($account, 'account'); // is this an array or object
              
dpm($result, 'result'); // did this return a strange result
              
dpm("INSERT INTO {users_roles} (uid, rid) values ({$account->uid}, $result)");
              
            }
         }
         else {
          
dpm($regcode . ' DID NOT EXIST');
         }
       }
}
?>

use "db_fetch_array(db_query(...))"

Alan D. - June 6, 2008 - 21:42

Alan Davison
www.caignwebs.com.au

Actual, ...

Alan D. - June 6, 2008 - 21:52

Like db_fetch_array, db_result requires a sql resultset too.

so you could go back to db_result(db_query($sql, $regcode->rid)) [edit]

Alan Davison
www.caignwebs.com.au

It Works!!!!!! the code

adfad666 - June 6, 2008 - 23:26

It Works!!!!!!

the code sucessfully assigns a role to a user based on a registration code they enter during registration.

now all I need to do is write an admin page that calls the list of roles and allows me to set the registration code there, and even add a new role and registration code all at once... currently i've done it all manually via phpmyadmin, but i'll save that for another day!

Thanks for your help Alan, much appreciated!!!

Adam

<?php
// $Id: regcoderole.module,v 0.1 $
/**
* @file
*   regcoderole.module
*/
function regcoderole_perm() {
  return array(
'administer registration codes');
}
function
regcoderole_user($op, &$edit, &$account, $category = NULL) {
    switch (
$op) {
      case
'register':
       
$form['regcoderolecode'] = array(
         
'#type' => 'textfield',
         
'#title' => t('Registration Code'),
         
'#default_value' => $regcode,
         
'#required' => TRUE,
         
'#description' => t('Please enter your registration code.'),
        );
        return
$form;
        break;
      case
'insert':
        
$regcode = trim($edit['regcoderolecode']);
         if (
strlen($regcode)) {
             
$sql = "SELECT rid FROM {role} WHERE rolekey = '%s'";
           if (
$result = db_result(db_query($sql, $regcode))) {
              
$sql = "INSERT INTO {users_roles} (uid, rid) values (%d, %d)";
              
db_query($sql, $account->uid, $result);             
            }
         }
         break;
       }
}
?>

Sweet

Alan D. - June 6, 2008 - 23:59

Nice job.

If you feel like sharing with the community, I could help write up a module for it. It wouldn't take too much work to create a interface for the reg codes.

Are you developing on D5 or D6?

Alan Davison
www.caignwebs.com.au

Yeah I've just applied for a

adfad666 - June 7, 2008 - 07:21

Yeah I've just applied for a CVS account so I could contribute the code as a new module, so your continued help would be a great help! I've seen a fair few requests for this so I think it'll be appreciated.

I'm developing for D5. The reason being I need the gallery2 module to integrate with my site, and there currently isn't a stable module for D6. That module syncs drupal usernames and roles with Gallery2, so then I can limit specific photo albums in Gallery2 to be shown to assigned roles. Now when people log in they will be able to see only the albums asigned to the role associated with their account...

Will need new role_keys table too :)

Alan D. - June 7, 2008 - 07:56

Just noticed what the role table was, lol

How hits for "admin", "administrator" and "developer" do you think there are out there.

Write up come clear specs, and I'll have a look.

Currently doing a custom image replacement for a personal site. Using Drupals new file handling mechanism and imagecache / imageapi for the handling. The code is coming out real clean so far. Still revisions and private file handling to factor in yet though :(

Alan Davison
www.caignwebs.com.au

aims for this module

adfad666 - June 7, 2008 - 09:29

Specs for the RegKeyRole Module:

Installation configuration

• Create new table role_keys with columns rid, rolekey

Assign to a user a pre-determined role based on a key entered on registration

• Insert a textfield on the registration page to enter the registration key
• On submit, look for the key in the rolekey column on the role_keys table and return the rid from the same row
• Insert the new account uid and the returned rid into the roles table

RegKeyRole administration page

• Look up all the roles as found in the roles table (except the two default roles) and any registration keys for that role as found in the role_keys table
• Display in three columns:
o 1st column: the name of the role
o 2nd column the current registration key
o 3rd column a textfield to change the registration key, with a submit button

• At the bottom of the page have two new textfields to be able to add a new role with registration key

Optional

• On user profile page have textfield to be able to submit extra registration codes to join other roles
• On profile page have section that lists the added roles as “member of the [role_name] group”

Sounds good

Alan D. - June 7, 2008 - 09:36

The only other thing that I can think of would be a limit on the number of times that a user would be allowed to try to enter a code. This would help prevent brute force attacks.

Have you done anything else other than the code bits submitted above?

If so, send through an email to alan@work [below] and I'll try and put something together tonight/tomorrow.

Alan Davison
www.caignwebs.com.au

I tried to email you but it

adfad666 - June 8, 2008 - 01:12

I tried to email you but it failed. if you can send me a msg to sugarfree_adam@'the mail that is hot'.com i'll try and reply to you all that i have so far. i haven't got much done except a bit of the admin page, because it was czech's euro2k8's opening game today, and since that is where i now live, i was obligated to go get drunk.

adam

Any Updates with making this into a module?

wcleong - July 9, 2008 - 00:27

Hello,
This functionality looks to be very useful for a site I'm trying to put together. Are there any updates to the code or progress in creating an admin interface for this?

Thanks,
Wes

Beta version

Alan D. - July 11, 2008 - 11:36

I've got a beta version here http://rctopos.com/sites/default/files/rolekey.zip, make sure you do some testing on your environment first. Adam or myself may release it at a future date, but at this stage I far too busy on other projects. There is only a version for Drupal 5. I could look at doing a port to D6 if there is interest.

Points of note:

You need the max permission to use the module, 'administer access control', I did this as you can assign any role to new users, fairly dangerous. Take care

There are options to assign via a code, or user selection of their membership group. Both handle a collection of roles for each group.

Role key is linked to 0 or more Roles that have 0 or more permissions. There is no tracking of role assignment, simply handles assignment of roles when the user joins.

Enjoy

Alan Davison
www.caignwebs.com.au

updates

wcleong - July 31, 2008 - 18:47

Thanks for that code! I don't know if anyone else is looking at this, but I updated some of the code to allow people to enter registration codes even after they have already created an account, they can enter it in their "edit account" settings. I'd probably prefer it to show up as an additional tab in the user settings, but I'm not much of a coder and I'm not sure how that's done.

The changes are to the rokekey.module file are....

Here is the new hook_user() function, I had to add two cases to the switch statement. The first is the 'form' case, this tells drupal to display the registration code form during account edits. The second case, 'update', runs when a user clicks save to change his account details, and calls the same function as the 'insert' case. Here is the code for this function (ignore the first and last php tags):

<?php
function rolekey_user($op, &$edit, &$account, $category = NULL) {
  switch (
$op) {
    case
'register':
      return
_rolekey_key_form_element();
    case
'form':
      return
_rolekey_key_form_element();
    case
'validate':
     
_rolekey_key_form_element_validate($edit, $account, $category);
      break;
    case
'insert':
     
_rolekey_key_form_element_submit($edit, $account, $category);
      break;
    case
'update':
     
_rolekey_key_form_element_submit($edit, $account, $category);
      break;
    case
'view':
      if(
variable_get('rolekey_show_rolekey_info', 0)) {
       
$items['rolekey'] = array('title' => t('Membership details'),
         
'value' => _rolekey_user_memberships($account),
         
'class' => 'rolekey',
        );
        return array(
t('History') => $items);
      }
  }
}
?>

Because the 'insert' and 'update' actions call the same function, we have to provide a check for the $edit['roles'] variable. For existing users this needs to be pre-populated with the current roles that the user is assigned, otherwise they will be reset when entering a registration code. I don't know if this is the best way to implement it, I'd happily take critiques.

So here is the modified function _rolekey_key_form_element_submit()

<?php
function _rolekey_key_form_element_submit(&$edit, $account, $category) {
if (!isset(
$edit['roles'])){
 
$result = db_query('SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = %d', $account->uid);
  while (
$role = db_fetch_object($result)) {
   
$edit['roles'][$role->rid] = $role->rid;
  }
}

 
$type = variable_get('rolekey_selection_type', 'textfield');
  if (
array_key_exists('rolekeycode', $edit) && $type != 'none') {
    if (
$type == 'textfield') {
     
$result = db_query("SELECT DISTINCT rr.rid FROM {rolekey_roles} rr LEFT JOIN {rolekey_keys} rk ON (rk.kid = rr.kid) WHERE rk.rolekey ='%s' AND rk.status = 1", trim($edit['rolekeycode']));
      while(
$role = db_fetch_object($result)) {
       
$edit['roles'][$role->rid] = $role->rid;
      }
    }
    else {
     
$keys = ($type == 'checkboxes') ? $edit['rolekeycode'] : array($edit['rolekeycode']);
      if(
is_array($keys)) {
       
$roles = array();

        foreach(
array_filter($keys) as $key) {
         
$result = db_query("SELECT rr.rid FROM {rolekey_roles} rr LEFT JOIN {rolekey_keys} rk ON (rk.kid = rr.kid) WHERE rk.kid ='%s' AND rk.status = 1", $key);
          while(
$role = db_fetch_object($result)) {
           
$roles[$role->rid] = $role->rid;
          }
        }
       
$edit['roles'] = $roles;
      }
    }
  }
}
?>

Subscribe..

vkr11 - October 25, 2008 - 23:58

This is a lot of info, I need this module too. Thanks for all the work.

- Victor
Better Way to Search Drupal.org | Drupal Jobs | Income Tax India

New link

Alan D. - October 26, 2008 - 02:37

There must have been a security change in the apache config somewhere as the default .htaccess is blocking zip files.

Try http://rctopos.com/sites/rolekey.zip instead

This does not include the above code by wcleong.

Alan Davison
www.caignwebs.com.au

Join role with password

francoud - November 10, 2008 - 10:15

I didnt know you were working on this. I've found this page too late :) In the meanwhile, I developed a module, for Drupal 5 only, which make able (authorized) users to join a given role using a password. Administrator can add a password to a role, since then users with the right authorization can join that role using the passsword (if they know it).

I tested in drupal 5 and it works, AFAIK. Maybe it can be usefull to others. I find it useful in my environment, using in conjunction with "forum access", to make selected people able to join a role - e.g. "user_of_forum_1" - without having to manually give them the role.

http://drupal.org/project/join_role_with_password

D6 Module

shunshifu - February 28, 2009 - 02:09

Was there ever a drupal 6 module made of Role Key. I'd sure like it.

Phil

Is there still any interest

Alan D. - March 1, 2009 - 12:01

Is there still any interest in the original version, rolekey, or does join_role_with_password tick all of the requirement boxes?

I have just fixed the A record due to a IP change in Dec, so the download will be working again soon.

Alan Davison
www.caignwebs.com.au

For Drupal 6

Helpermedia - November 10, 2008 - 09:47

If anybody wants to use this kind of functionality (adding roles during registration) in Drupal 6, you need to fill the $edit parameter with extra roles in hook_user when $op is 'insert', assigned roles via SQL inserts will be overruled by the contents of the $edit parameter ($edit['roles'] is default empty)

An example:

function your_module_user($op, &$edit, &$account, $category = NULL) {
  if ($op == 'insert') {
    // Add role
    $edit['roles'] += array($your_rid => 'your_role_name');
  }
}

Adam and Alan -- How about a "Register As" option?

GreyHawk - April 27, 2009 - 14:36

Not sure how to rig it, but if you want to give users the option to register as staff or client by simply clicking a link that says "Register as a client" or "Register as a staffmember" and keep the role selection and/or registration code portion hidden; they'd get a normal user registration screen with the role pre-selected.

Any ideas on how that would work, and if it could be included here (perhaps as a "silent reg code" based on a relative URL path or something)?

Or any suggestions about whether it would make more sense to incorporate it with the auto-assign role module?

(also see my comment here for more clear (?) description of it, as a comment I left on a related topic)

upgrade to 6

ozjett - May 18, 2009 - 00:02

Has anybody got this working on 6 yet I may be able to sponsor the development

I didn't have the time to

Alan D. - May 18, 2009 - 07:20

I didn't have the time to commit the module that myself and Adam were working on until the "join role with password" was released: http://drupal.org/node/264854#comment-1084287

Which one are you referring to? I have not compared these to see how much overlap there is, but could consider releasing this (role key) if the overlap is minimal and there is some demand for it.

Alan

Alan Davison
www.caignwebs.com.au

upgrade to 6

ozjett - May 20, 2009 - 07:43

Hi Alan I have not being able to evauate join role as dev snapshot fails on 6.11 I would love to see role key released I have being trying to upgrade the code to 6 without luck so far (I have no Idea what I am doing).

Primary release

Alan D. - May 20, 2009 - 14:22

I've pushed this into a 5.x-dev branch and will look at porting to 6.x when I have some spare time.

http://drupal.org/node/468058

Alan Davison
www.caignwebs.com.au

Primary release

ozjett - May 20, 2009 - 23:15

Thanks Alan
I am happy to help in anyway I am not much of a coder but and do testing if needed.

Excellent. I hate

Alan D. - May 20, 2009 - 23:37

Excellent. I hate testing...

I may look at a quick port tonight.

Alan Davison
www.caignwebs.com.au

First 6 port

Alan D. - May 21, 2009 - 14:42

K, in the next 12 hours there will be a dev release for D6.

You can get it earlier via CVS, DRUPAL-6--1 branch if you are really keen. (@cvs.drupal.org:/cvs/drupal-contrib/contributions/modules/rolekey)

I don't use the module, so my testing has been fairly limited in both versions. I will take your offer to "sponsor the development" in time if you like and let you do full test on it?!

If you do, can you consider both the UI as a first time user, any unexpected results, and any bugs. The port took a lot more work than I expected (4 1/2 hours: 1 hour due to new feature for the field on the user edit page, and another hour searching for the bug created by not renaming the hook_theme function to rolekey_theme), so testing has been very limited. Create a new issue for each and I get onto fixes / suggestions.

Note to self & others doing porting: search for "hook_.*(", this can save an hours debugging!

Cheers

Alan Davison
www.caignwebs.com.au

First 6 port

ozjett - May 22, 2009 - 02:21

I shall start testing tonight and over the weekend

great post

crutch - May 23, 2009 - 02:45

I just read through the whole year of posts here, really great stuff! I'm looking forward to testing/using this module.

Cool. Just one word: Test, test, test. ;)

Alan D. - May 23, 2009 - 03:12

I've turned on the "Show development snapshots" so they are now appearing on the main project page, so the dev versions of Registration Role Keys for both Drupal 5 and 6 can be found here: http://drupal.org/project/rolekey

I'm not using this module directly, it was more of an challenge while helping out on the forums. I've got two upcoming projects that are going to require a lightweight e-comm membership system that is not currently available (to the best of my knowledge), which I'm just starting on the e-comm side of things at the moment. The logic used here will form the basis of the membership system. I am not interested in a full-shop solution to the membership issue as there is too much of a performance hit.

Anyway, let me know how you get on. Report back on bugs, doco, and any UI issues.

Cheers

Alan

Alan Davison
www.caignwebs.com.au

mm thank you guys..

ilo - May 23, 2009 - 15:59

Just looked for this kind of functionality and found a complete working published module. Well done. I'll be tweaking a site configuration these days, so I guess I would create some issue for it, the list is quite clean now!! hehe

thank you

shunshifu - August 12, 2009 - 23:41

thank you thank you thank you. this was a much needed module

Auto assign role based on registration code

ozjett - May 25, 2009 - 05:31

I did not get much testing done due to family issue but have installed it on my dev site which had the old 5 version installed and so far it looks great there may be a issue with the show roles on the user infomation page But I will install on a fresh site to do proper testing and try to give you back a solution not just a problem :)
thanks again for all your work.

version 5 update

ozjett - May 25, 2009 - 05:37

just an update on the 5.X version I have had this running on my production site for the last 4 - 5 months with 35 roles and 1600 users and found it to be flawless so in my mind if the module has not changed you could consider this stable.

Cool, thats the feedback I

Alan D. - May 25, 2009 - 09:49

Cool, thats the feedback I like ...

The 5.x-1.0 release is the exact same code as the zip above without the "My account" addition.

The D5 dev version includes this modification that allows the form to be included on the User edit page. Apart from that, I think that the module has filled its niche and I will not plan anything else for the Drupal 5 release. New features will be focused towards the Drupal 6 release.

Note: The role-key-5.x-1.0-dev version got packaged up with a couple bugs, so I'm hiding this until the packaging script updates this.

Alan

Alan Davison
www.caignwebs.com.au

Subscribe

glennnz - August 12, 2009 - 23:56

Subscribe

I like this module but it's

adetoyan - August 28, 2009 - 07:15

I like this module but it's lacking one thing. And that's automatic generation of reg keys or codes. Or does it integrate with reg codes? I don't think I would like to manually enter reg keys for a site that will host 1000 + users

I'm a Nigerian and I'm proud of it
www.kainosnigeria.com

Add a feature request in the

Alan D. - August 28, 2009 - 13:09

Add a feature request in the modules issue queue.

Alan Davison
www.caignwebs.com.au

 
 

Drupal is a registered trademark of Dries Buytaert.