/*
 * Created on 08-Oct-2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package uk.ac.roe.wfau;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author mar
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class WSALogin {
  public static final String DEFAULT_NAME="not logged in";
  static public void setLoginName (HttpServletRequest req) {
      String authhead = req.getHeader("Authorization");
      String userPassDecoded = null;
      String user=null;
      byte mydata[];
      if (authhead != null) {
          sun.misc.BASE64Decoder base64 = new sun.misc.BASE64Decoder();
          try {
            // cut off the "Basic " string
              mydata = base64.decodeBuffer(authhead.substring(6));
        } catch (IOException e) {
            mydata=null;
        }
        if (mydata != null){
          userPassDecoded = new String(mydata);
          int p = userPassDecoded.indexOf(":");
          if (p != -1) {
             user = userPassDecoded.substring(0, p);
          } 
          else {
              user = DEFAULT_NAME;
          }
        }
        else {
            user = DEFAULT_NAME;
        }
      }
      else {
          user = DEFAULT_NAME;
      }
      try {
      HttpSession session = req.getSession();
      session.setAttribute("user", user);
      }
      catch (Exception e){
      }
  }
  static public String getLoginName (HttpServletRequest req) {
      HttpSession session = req.getSession();
      String user=null;
      try {
      user=session.getAttribute("user").toString();
      } 
      catch (Exception e){
          user=null;
      }
      if (user != null){
          return user;
      }
      else {
          String authhead = req.getHeader("Authorization");
          String userPassDecoded = null;
          user=null;
          byte mydata[];
          if (authhead != null) {
              sun.misc.BASE64Decoder base64 = new sun.misc.BASE64Decoder();
              try {
                // cut off the "Basic " string
                  mydata = base64.decodeBuffer(authhead.substring(6));
            } catch (IOException e) {
                mydata=null;
            }
            if (mydata != null){
              userPassDecoded = new String(mydata);
              int p = userPassDecoded.indexOf(":");
              if (p != -1) {
                 user = userPassDecoded.substring(0, p);
                 return user;
              } 
              else {
                  return DEFAULT_NAME;
              }
            }
            else {
                return DEFAULT_NAME;
            }
          }
          else {
              return DEFAULT_NAME;
          }        
      }
  }
}
