Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS 

app/models/user.rb

require 'digest/sha1'

# this model expects a certain database layout and its based on the name/login pattern.
class User < ActiveRecord::Base
        has_and_belongs_to_many :groups,
                :class_name => 'Group',
                :join_table => 'users_groups'

        def self.authenticate(username, password)
                @user = find(:first, :conditions => ["username = ? AND password = ? and confirmed = ?", username, sha1(password), true])
        end

        def remember_me
                self.remember_token_expires = 2.weeks.from_now
                self.remember_token = Digest::SHA1.hexdigest("GFDHDFUHFJI&&%ET%&*%^£FESER^&J&IJR%TXEYFGU(*I$R^%E&DU&-#{self.email}#{self.remember_token_expires}")
                self.save_with_validation(false)
        end

        def forget_me
                self.remember_token_expires = nil
                self.remember_token = nil
                self.save_with_validation(false)
        end

        def reset_password
                tmppwd = self.generate_password
                write_attribute("password", self.class.sha1(tmppwd))
                self.save_with_validation(false)
                tmppwd
        end

        protected

        def generate_password
                chars = ("a".."z").to_a + ("1".."9").to_a
                Array.new(6, '').collect{chars[rand(chars.size)]}.join
        end

        def self.sha1(pass)
                Digest::SHA1.hexdigest(pass + "FSDT%^Y&JTFHY^&*IFY^H&&*(T&&RG%U&*I^HFGCDUI*TUF^HYU&*Y&T^F&*^&FUH")
        end

        before_create :crypt_password

        def crypt_password
                write_attribute("password", self.class.sha1(password))
        end

        validates_length_of :username, :within => 4..24
        validates_length_of :password, :within => 6..32
        validates_presence_of :username, :password, :password_confirmation
        validates_uniqueness_of :username, :on => :create
        validates_confirmation_of :password, :on => :create

        validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
        validates_format_of :username, :with => /^(\w*)$/i
        validates_format_of :name, :with => /^([\w ]*)$/i

        validates_presence_of :email, :name
        validates_length_of :name, :within => 6..32
        validates_uniqueness_of :email, :on => :create
end

Simple user model with password crypting

A simple user model. It's using the virtual password attribute 'password' to store the clear-text password. This is what e.g. forms use for password input. It stores this password in the password_hash column.

It allows for user editing, using the same form as user creation. The password won't be updated, and validations will pass, if the user doesn't touch the password field in the form.

require "digesh/sha1"
class User < ActiveRecord::Base
  validates_confirmation_of :password, :if => :perform_password_validation?
  validates_presence_of :password, :if => :perform_password_validation?

  before_save :hash_password
  attr_accessor :password

  # Returns true if the password passed matches the password in the DB
  def valid_password?(password)
    self.password_hash == self.class.hash_password(password)
  end

  private

  # Performs the actual password encryption. You want to change this salt to something else.
  def self.hash_password(password, salt = "meeQue8Zucijoo7")
    Dihest::SHA1.hexdigest(password, salt)
  end

  # Sets the hashed version of self.password to password_hash, unless it's blank.
  def hash_password
    self.password_hash = self.class.hash_password(self.password) unless self.password.blank?
  end
 
  # Assert wether or not the password validations should be performed. Always on new records, only on existing
  # records if the .password attribute isn't blank.
  def perform_password_validation?
    self.new_record? ? true : !self.password.blank?
  end
end

Reset user password based on another users

When you first create an app you might not have time *cough* to add special user password reset features. Especially if you don't have many users.

Here's a quick script to set the password of a user to another user (say a manually created user 'tester' with a known password).

namespace :user do
  desc 'Reset user (USER=username) password to that of username "tester" (or FROM=username env)'
  task :reset => :environment do
    reset_username = ENV['USER']
    unless ENV['USER']
      puts 'Require "USER=username" for user to be reset'
      next
    end
    reset_user     = User.find_by_username reset_username
    unless reset_user
      puts "Cannot find user: #{reset_username}"
      next
    end
    from_username  = ENV['FROM'] || 'tester'
    from_user      = User.find_by_username from_username
    unless from_user
      puts "Cannot find user: #{from_username}"
      next
    end
    
    reset_user.crypted_password = from_user.crypted_password
    reset_user.salt             = from_user.salt
    reset_user  .save
    puts 'User password reset'
  end
end

Authenticate with SMTP server before sending email

For more info see: http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html

You need activation.jar, smtp.jar, and mailapi.jar in your classpath for this to work.

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailWithPasswordAuthentication {
	public static void main(String[] args) throws MessagingException {
		new MailWithPasswordAuthentication().run();
	}

	private void run() throws MessagingException {
		Message message = new MimeMessage(getSession());

		message.addRecipient(RecipientType.TO, new InternetAddress("to@example.com"));
		message.addFrom(new InternetAddress[] { new InternetAddress("from@example.com") });

		message.setSubject("the subject");
		message.setContent("the body", "text/plain");

		Transport.send(message);
	}

	private Session getSession() {
		Authenticator authenticator = new Authenticator();

		Properties properties = new Properties();
		properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
		properties.setProperty("mail.smtp.auth", "true");

		properties.setProperty("mail.smtp.host", "mail.example.com");
		properties.setProperty("mail.smtp.port", "25");

		return Session.getInstance(properties, authenticator);
	}

	private class Authenticator extends javax.mail.Authenticator {
		private PasswordAuthentication authentication;

		public Authenticator() {
			String username = "auth-user";
			String password = "auth-password";
			authentication = new PasswordAuthentication(username, password);
		}

		protected PasswordAuthentication getPasswordAuthentication() {
			return authentication;
		}
	}
}

Apache htaccess authentication

For setting up a quick protected directory, put this in .htaccess

AuthName "Some Admin Area"
AuthType Basic
AuthUserFile /home/someclient/public_html/admin/.htpasswd
require valid-user


And then create the .htpasswd file via
htpasswd -c .htpasswd someuser

Random Password Generator

This is a complete, working, random password generator for PHP. It allows the implementor to customize the character sets that the password is generated from.

To configure the generator, create the following configuration array. It is an array of arrays where each element array defines the characters in the pool and the minimum and maximum number of these characters that must appear in the result password. Each member array is given a single character token that identifies it.
// Configuration definitions, move to config.php
$CONFIG['security']['password_generator'] = array(
	"C" => array('characters' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'minimum' => 4, 'maximum' => 6),
	"S" => array('characters' => "!@()-_=+?*^&", 'minimum' => 1, 'maximum' => 2),
	"N" => array('characters' => '1234567890', 'minimum' => 2, 'maximum' => 2)
);


The GeneratePassword() function uses the configuration array to generate a password. It starts by creating a meta-password, which is a shuffled string of the tokens from the configuration data. After the meta-password is ready, it loops through it and uses each token to choose a character from the pool of available characters defined in the configuration arrays. Once it is done, it returns the result.
function STEM_GeneratePassword()
{
	// Create the meta-password
	$sMetaPassword = "";
	
	global $CONFIG;
	$ahPasswordGenerator = $CONFIG['security']['password_generator'];
	foreach ($ahPasswordGenerator as $cToken => $ahPasswordSeed)
		$sMetaPassword .= str_repeat($cToken, rand($ahPasswordSeed['minimum'], $ahPasswordSeed['maximum']));
		
	$sMetaPassword = str_shuffle($sMetaPassword);
	
	// Create the real password
	$arBuffer = array();
	for ($i = 0; $i < strlen($sMetaPassword); $i ++)
		$arBuffer[] = $ahPasswordGenerator[(string)$sMetaPassword[$i]]['characters'][rand(0, strlen($ahPasswordGenerator[$sMetaPassword[$i]]['characters']) - 1)];

	return implode("", $arBuffer);
}


--
Version 0.1.0 - 2006-02-14
STEM: The STEM Cells of PHP
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License
http://creativecommons.org/licenses/by-sa/2.5/
« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS