Sunday, June 3, 2012

Quick start pylons authentication.

Authentication is vital function in Today's some web applications.
Pylons framework that my powerful tool have useful authenticate function using authkit.
Today, I tried to make simple portal using authkit.
$ cd ~/
$ easy_install "AuthKit>=0.4.3,<=0.4.99"
$ mkdir webapplications
$ cd webapplications
$ paster create -t pylons auth1
$ emacs -nw ./auth1/auth1/config/
  from pylons.wsgiapp import PylonsApp
  from routes.middleware import RoutesMiddleware

+ from auth1.config.environment import load_environment

  def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
      """Create a Pylons WSGI application and return it

  from pylons.wsgiapp import PylonsApp
  from routes.middleware import RoutesMiddleware

  def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
      """Create a Pylons WSGI application and return it
      app = CacheMiddleware(app, config)

      # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
+     import authkit.authenticate

      if asbool(full_stack):
          # Handle Python exceptions
          app = ErrorHandler(app, global_conf, **config['pylons.errorware'])

+         app = authkit.authenticate.middleware(app, app_conf)

 # Display error documents for 401, 403, 404 status codes (and
          # 500 when debug is disabled)
          if asbool(config['debug']):
$ emacs -nw ./auth1/development.ini
cache_dir = %(here)s/data
beaker.session.key = auth1
beaker.session.secret = somesecret

# setup authkit
authkit.setup.enable = true
authkit.setup.method = form, cookie
authkit.form.authenticate.user.type = authkit.users.sqlalchemy_driver:UsersFromDatabase = auth1.model
authkit.cookie.secret = secret string
authkit.cookie.signoutpath = /signout

# If you'd like to fine-tune the individual locations of the cache data dirs
# for the Cache data, or the Session saves, un-comment the desired settings
# here:
#beaker.cache.data_dir = %(here)s/data/cache
#beaker.session.data_dir = %(here)s/data/sessions

# SQLAlchemy database URL
#sqlalchemy.url = sqlite:///%(here)s/development.db
sqlalchemy.url = mysql://[user]:[passuword]@localhost:3306/auth1
$ mysql -u root -p
mysql> create database auth1;
$ emacs -nw ./auth1/auth1/
  """Setup the hello application"""
  import logging

+ from hello.config.environment import load_environment

  log = logging.getLogger(__name__)

  def setup_app(command, conf, vars):
      """Place any commands to setup hello here"""
      load_environment(conf.global_conf, conf.local_conf)
      """Setup the auth1 application"""
      import logging

+ from auth1.config.environment import load_environment
+ from auth1 import model
+ from auth1.model import meta

  log = logging.getLogger(__name__)

  def setup_app(command, conf, vars):
      """Place any commands to setup auth1 here"""
      load_environment(conf.global_conf, conf.local_conf)
+     # Create the tables if they don't already exist
+     meta.metadata.create_all(bind=meta.engine)
+     from authkit.users.sqlalchemy_driver import UsersFromDatabase
+     meta.metadata.bind = meta.engine
+"Adding the AuthKit model...")
+     users = UsersFromDatabase(model)
+     meta.metadata.create_all(checkfirst=True)
+"Adding roles and users...")
+     users.role_create("delete")
+     users.user_create("foo", password="bar")
+     users.user_create("admin", password="opensesame")
+     users.user_add_role("admin", role="delete")
+     meta.Session.commit()
$ paster setup-app development.ini
$ mysql -u root -p
mysql> connect auth1;
mysql> show tables;
$ emacs -nw ./auth1/auth1/lib/
from authkit.permissions import ValidAuthKitUser
from authkit.permissions import HasAuthKitRole
from authkit.authorize.pylons_adaptors import authorized

is_valid_user = ValidAuthKitUser()
$ emacs -nw ./auth1/auth1/lib/
  # Import helpers as desired, or define your own, ie:
  #from webhelpers.html.tags import checkbox, password

+ from auth1.lib import auth
  from routes import url_for
$ paster controller account
  import logging

  from pylons import request, response, session, tmpl_context as c
  from pylons.controllers.util import abort, redirect_to

+ from auth1.lib.base import BaseController, render

  log = logging.getLogger(__name__)

  class AccountController(BaseController):

+     def signin(self):
+         if not request.environ.get('REMOTE_USER'):
+             abort(401)
+         else:
+             return render('/derived/account/signedin.mako')

+     def signout(self):
+         return render('/derived/account/signedout.mako')
$ paster controller portal
  import logging

  from pylons import request, response, session, tmpl_context as c
  from pylons.controllers.util import abort, redirect_to

+ from auth1.lib.base import BaseController, render

+ from authkit.permissions import ValidAuthKitUser
+ from authkit.authorize.pylons_adaptors import authorize

+ from auth1.lib import auth

  log = logging.getLogger(__name__)

  class PortalController(BaseController):
+     @authorize(ValidAuthKitUser())
      def index(self):
!         return render('portal.mako')
$ emacs -nw ./auth1/auth1/templates/portal.mako
$ mkdir ./auth1/auth1/templates/derived
$ mkdir ./auth1/auth1/templates/derived/account
$ emacs -nw ./auth1/auth1/templates/derived/account/signedin.mako
<%inherit file="/base/index.mako"/>

<%def name="title()">Signed In</%def>
<%def name="heading()"><h1>Signed In</h1></%def>

<p>You are signed in as ${request.environ['REMOTE_USER']}.
<a href="${h.url_for(controller='account', action='signout')}">Sign out</a></p>
$ emacs -nw ./auth1/auth1/templates/derived/account/signedout.mako
<%inherit file="/base/index.mako"/>

<%def name="title()">Signed Out</%def>
<%def name="heading()"><h1>Signed Out</h1></%def>

<p>You have been signed out.</p>
$ mkdir ./auth1/auth1/templates/base
$ emacs -nw ./auth1/auth1/templates/base/index.mako
<div id="hd">
  <div class="yui-gc">
<div class="yui-u first">
<div class="yui-u">
      %if h.auth.authorized(h.auth.is_valid_user) and not (request.urlvars['controller'] == 'account' and request.urlvars['action'] == 'signout'):
 <p>Signed in as ${request.environ['REMOTE_USER']},
<a href="${h.url_for('signout')}">Sign out</a></p>
<a href="${h.url_for('signin')}">Sign in</a></p>
$ emacs -nw ./auth1/auth1/config/
def make_map():
    """Create, configure and return the routes Mapper"""
    map = Mapper(directory=config['pylons.paths']['controllers'],
    map.minimization = False

    # The ErrorController route (handles 404/500 error pages); it should
    # likely stay at the top, ensuring it can always be resolved
    map.connect('/error/{action}', controller='error')
    map.connect('/error/{action}/{id}', controller='error')



+   map.connect('signout', '/signout', controller='account', action='signout')
+   map.connect('signin', '/signin', controller='account', action='signin')

    return map
$ mkdir ./auth1/auth1/public/css
$ emacs -nw ./auth1/auth1/public/css/main.css
#hd p {
text-align: right;
padding-right: 20px;
padding-top: 5px;

Monday, January 9, 2012

I think port to ARM.

I'm thinking my own OS to port x86 to ARM.
I have to control ARM chip.
I will try to design and make program on ARM.
Install gcc for ARM.
$ sudo apt-get install gcc-arm-linux-gnueabi
Install ARM qemu.
$ sudo apt-get install qemu qemu-kvm qemu-kvm-extras
Write program by ARM assemble(hello world) and check ARM registers.
    .align 2
    .global _start

# write system call
sys_write = 0x900004
# exit system call
sys_exit = 0x900001

# Program entry
    ldr r1, msg
    mov r0, #1
    ldr r2, msg_sz
    swi #sys_write

    mov r0, #0
    swi #sys_exit

msg:    .long msg_str
msg_sz: .long msg_sz0

    .align 2

msg_str: .asciz "Hello, world\n"

    .align 2
    msg_sz0 = . - msg_str

    .align 2
data: .long 0
Compile and link program.
$ arm-linux-gnueabi-as -o hello.o hello.s                 
$ arm-linux-gnueabi-ld hello hello.o
Run software on ARM qemu.
$ qemu-arm ./hello

Hello, world

Reading ATA device sector

I should write to read ATA device sector.
  1. First, We will wait until the port 0x03f6 is zero using device selection protocol.
  2. Second, Next, We will set device number to port 0x01f6(device/head register).
  3. Next, We will set 0x02 to port 0x03f6(device control register) and set 0x00 to port 0x01f1(features register).
  4. Then, We will prepare for reading sector.Details below.
  5. out8(0x01f2, 1); // Set read count.
    out8(0x01f3, sector & 0xff); // Set sector number to register.
    out8(0x01f4, (sector >> 8) & 0xff); // Set cylinder low to register.
    out8(0x01f5, (sector >> 16) & 0xff); // Set cylinder High to register.
    out8(0x01f6, ((sector >> 24) & 0x0f) | 0x40); // Set Head number to register.
  6. Finally, We will read sector data by setting 0x20 to port 0x01f7.
    1. out8(0x01f7, 0x20); // read data.
for(i = 0; i < SECTOR_SIZE; i++) {
  buf[i] = inw(0x01f0);

Thank you.

Wednesday, December 28, 2011

ATA device control

I added new driver.
It has ATA and ATAPI control function.
HDD is controlled PIO mode and LBA.

  • First, Initialize ATA and ATAPI device.
Execute soft reset.

Read Cylinder Low inb(0x01f4);

Read Cylinder High inb(0x01f5);

Input Cylinder Low and High to get device type.

(We can confirm ATA device when Cylinder High and Low is Zero.

 We can confirm ATAPI device when Cylinder High is 0xeb and Cylinder Low is 0x14.)

Identify device.

Execute device selection protocol.

Wait until BSY to Zero.
Wait DRQ to active.
Read 256 byte sectors for prepare.

  • Next, read sector from ATA device.
I will write this section tomorrow.... sorry.

Thursday, December 22, 2011

Build ICS

OS:Ubuntu 11.10 x86

download repo utility.
$ curl > ~/bin/repo
$ chmod a+x ~/bin/repo
Create directory and initialize git repository.
$ mkdir android-ics
$ cd andorid-ics
$ repo init -u -b android-4.0.1_r1
$ repo sync

$ bash
$ source ./build/
$ lunch full-eng
$ time make -j2 2>&1 |tee make.log
That method will be to the error on Ubuntu 11.10(x86).
$ emacs -nw build/core/combo/

$ emacs -nw external/gtest/include/gtest/internal/gtest-param-util.h
+#include   // 40 line

$ emacs -nw external/oprofile/libpp/format_output.h
 -               mutable counts_t & counts;
 +               counts_t & counts;  // 94 line

$ emacs -nw frameworks/compile/slang/
-local_cflags_for_slang := -Wno-sign-promo -Wall -Wno-unused-parameter -Werror
+local_cflags_for_slang := -Wno-sign-promo -Wall -Wno-unused-parameter  # 22line

$ emacs -nw external/llvm/lib/Support/Mutex.cpp
 #include "llvm/Config/config.h"
 #include "llvm/Support/Mutex.h"
+#undef ENABLE_THREADS  // 16 line

$ emacs -nw external/llvm/lib/Support/Signals.cpp

+#undef HAVE_DLFCN_H  // 28 line

$ emacs -nw external/llvm/lib/Support/Threading.cpp
 #include "llvm/Support/Mutex.h"
 #include "llvm/Config/config.h"
+#undef LLVM_MULTITHREADED  // 19 line

$ source build/
$ lunch full-eng
$ make -j2
launch emulator
$ emulator
But.... I failed to display AndroidOS home screen, after I succeed to launch emulator.

Sunday, December 4, 2011

Review English study in November

I reviewed English studying in November.
I was able to hear some English.

  • Famous peoples interview on TV.
  • Talk on Movies.
  • CD for practice.
I did practice below.
  1. I was hearing English CD on Commuter Train.
  2. I was hearing high speed English CD on Commuter Train.
  3. I was writing English, after I was hearing high speed English CD.
  4. I read aloud in English.(Very easy Englishes)
I keep to try these practice in December. and I restart implement my own OS a little :-)


Sunday, November 13, 2011

Device management system (2)

I added new function called products and functions management!
It's so cool.

It can download matrix file device and product functions.
I need to implement more new function.