Why won't APEX authorization scheme hold stored username? - oracle-apex

I have an authorization scheme for my application that checks first if the username entered is a username in the system and then whether the user has access to this particular application. The login issue I am having is that the user will login in once and get denied and have to login a second time and it works. I think the issue is that the :APP_USERNAME is not stored for the first login attempt and then is stored in the application for the second try. I know there has to be a way around this, but I have yet to figure it out.
u_id number := null;
app_id number := null;
auth_id number := null;
authorized number(1,0) := 0;
auth_status char := 'f';
failure_reason varchar2(200) := null;
begin
begin
select id into u_id from user where username=:APP_USERNAME;
exception
when NO_DATA_FOUND then
u_id := null;
failure_reason := 'User not found:' || :APP_USERNAME;
end;
select id into app_id from lkup_application where name='Application Name';
if (u_id is not null) then
begin
select id into auth_id from authorization where application_id = app_id and user_id = u_id;
exception
when NO_DATA_FOUND then
auth_id := null;
failure_reason := 'User not authorized from authorization table.';
end;
end if;
if (auth_id is not null) then
authorized := 1;
auth_status := 's';
end if;
insert into access_audit values(null, :APP_USER, app_id, current_timestamp, auth_status, failure_reason);
commit;
return (authorized = 1);
end;```

Well, it is :APP_USER, not :APP_USERNAME so I suggest you use it.

Related

what will be the Authorization schemes for new user? in oracle apex

FUNCTION my_auth (
p_username IN varchar2,
p_password IN varchar2)
RETURN BOOLEAN AS
found number := 0;
BEGIN
SELECT 1 INTO FOUND FROM users
WHERE upper(email)=upper(p_username)
AND upper(password)=upper(p_password)
AND is_activated=1;
RETURN TRUE;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN FALSE;
END;
/* I have now three users 'admin','guest','other'
and the have following authorization administration,view only,edit.
if another user signs up in application what will be his/her authorization.
i want he will be allotted edit privilege automatically. all the new user will get the edit privileges. how can i do it?*/
You can create various authorization schemes according to functional need.
For eg. You can create different authorization schemes such as for create,update,delete,readonly etc.
FUNCTION create_auth (p_username IN varchar2,
p_password IN varchar2)
RETURN BOOLEAN AS
found number := 0;
BEGIN
SELECT 1 INTO FOUND FROM users
WHERE upper(email)=upper(p_username)
AND upper(password)=upper(p_password)
AND is_activated=1
AND ROLE='create';
RETURN TRUE;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN FALSE;
END;
Above functions return true/false based on role exist to user.
Similarly you can create edit_auth(authorization) and user role can be edit/update then that authorization you can apply to editable component of page.
For more information about authorization please check http://docs.oracle.com/cd/E59726_01/doc.50/e39147/sec_authorization.htm#HTMDB25783
Hope this will help you!

Golang setCookie() failed after template Execute()

As a beginner of GO, I've got a situation as following:
t, err := template.ParseFiles("/template/login.tpl")
err = t.Execute(w, nil) //if executed before SetCookie
http.SetCookie(...) //failed, browser received nothing
If the sequence is changed, to SetCookie first, it'll work.
My plan was to ParseForm() username and password in login.tpl, if success, a sessionID would be sent by SetCookie. But now SetCookie() must be placed before login.tpl is Executed, which also makes ParseForm() run before login.tpl is executed :
r.ParseForm( ) //ParseForm() works even before template is executed
email := r.FormValue("email")
pass := r.FormValue("pass")
var loginPass = checkLogin(email, pass) //verify username and password
if loginPass == true { //if correct
cookie1 := http.Cookie{Name: "test", Value: "testvalue", Path: "/", MaxAge: 86400}
http.SetCookie(w, &cookie1) //setCookie works
fmt.Println("Login success: ", email)
} else { //if incorrect username or pass
fmt.Println("Please login: ", email)
}
t, err := template.ParseFiles("/template/login.tpl")
err = t.Execute(w, nil) //now template execution is here, also works
But why it should be written like this? Please anyone give me some advice! Thanks a lot.
This is a common error tied to the HTTP protocol working: the cookie is sent in a header of the HTTP respo7nse, which cannot be changed after the body start being sent.
So, when you do the t.Execute(w, nil) call, you start writing the body of the response and thus cannot add cookies afterwards.
This is the exact same reason why in PHP the session_start() call must be the very first instruction of the page, even before any whitespace.

Delphi IdHTTP Post on Django-created Form

I'm posting the login-data from delphi on a django-created-form which runs on my localhost. Like this:
procedure TForm1.btnPostClick(Sender: TObject);
var
IdHTTP: TidHTTP;
auth: TStringList;
test,token:string;
begin
IdHTTP := TidHTTP.Create(nil);
IdHTTP.Request.Accept :='text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
IdHTTP.Request.AcceptCharSet :='iso-8859-1, utf-8, utf-16, *;q=0.1';
IdHTTP.Request.AcceptEncoding :='deflate, gzip, identity, *;q=0';
IdHTTP.Request.Connection :='Keep-Alive';
IdHTTP.Request.ContentType :='application/x-www-form-urlencoded';
token := IdHTTP.Get('http://localhost:8000/accounts/signup/');
token := copy(token, AnsiPos('csrfmiddlewaretoken', token) + 28, 32);
IdHTTP.Request.CustomHeaders.Clear;
with IdHTTP.Request.CustomHeaders do
begin
AddValue('X-CSRFToken',token);
Values['COOKIE']:='';
//if IdHTTP2.CookieManager.CookieCollection.count > 0 then
// Add('COOKIE: '+token);
end;
try
auth := TStringList.Create;
auth.Add('csrfmiddlewaretoken='+ token);
auth.Add('first_name=' + edtVorname.Text);
auth.Add('last_name=' + edtName.Text);
auth.Add('function=' + edtFunction.Text);
auth.Add('company=' + edtCompany.Text);
auth.Add('country=' + edtCountry.Text);
auth.Add('email=' + edtEmail.Text);
auth.Add('password1=' + edtPassword.Text);
auth.Add('password2=' + edtPasswordAgain.Text);
//IdHTTP.Request.CustomHeaders.AddValue('Accept-Language', 'en-EN');
//IdHTTP.Request.CustomHeaders.AddValue('Referer',
IdHTTP.post('http://127.0.0.1:8000/accounts/signup/', auth);
except
end;
end;
Whenever it gets until the Line with the post
IdHTTP.post('http://127.0.0.1:8000/accounts/signup/', auth);
Im getting the 403 error "Forbidden". My guess is im sending the CSRF-Token wrong
because from the python debugger I see being caught in
if csrf_token is None:
# No CSRF cookie. For POST requests, we insist on a CSRF cookie,
# and in this way we can avoid all CSRF attacks, including login
# CSRF.
return self._reject(request, REASON_NO_CSRF_COOKIE)
But HOW is it supposed to be? How do I need to send this csrf-token?
P.S Well I think the problem was that per default HandleRedirects is set to True and it gave me the 403. The cookievalue in the latest Django versions is usually called csrftoken and not X-CSRFToken how I did here.
You shouldn't set cookie by yourself. When Django response with a form and django.middleware.csrf.CsrfViewMiddleware is in your list of middleware classes (more on https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/), it should already set csrftoken cookie. So you only have to read value of this cookie and set it to csrfmiddlewaretoken form field.
Also don't forget to set UserAgent in your request. Without UserAgent Indy (Delphi 2010) and Django 1.8 won't cooperate with each other.
I don't know how to add csrfmiddlewaretoken field on redirects so I did it without redirects!
Here is my code:
uses
IdURI, IdCookie;
...
procedure TForm1.btnLoginClick(Sender: TObject);
var
idHTTP: TIdHTTP;
token: AnsiString;
stream: TStringStream;
params: TStringList;
cookie: TidCookieRFC2109;
begin
idHTTP := TIdHTTP.Create(nil);
stream := TStringStream.Create;
params := TStringList.Create;
try
idHTTP.AllowCookies := True;
idHTTP.HandleRedirects := False;
//even if HandleRedirects := False, you must have OnRedirect event (don't know why)
idHTTP.OnRedirect := IdHttpOnRedirect;
IdHTTP.Request.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8';
IdHTTP.Request.AcceptCharSet := 'iso-8859-1, utf-8, utf-16, *;q=0.1';
IdHTTP.Request.AcceptEncoding := 'gzip, deflate, sdch';
IdHTTP.Request.Connection := 'Keep-Alive';
IdHTTP.Request.ContentType := 'application/x-www-form-urlencoded';
idHTTP.Request.UserAgent := 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36';
idHTTP.Request.CharSet := 'utf-8';
idHTTP.Get('http://www.ttaksa.si/login/');
cookie := idHTTP.CookieManager.CookieCollection.Cookie['csrftoken', '.www.ttaksa.si'];
token := cookie.Value;
params.Values['csrfmiddlewaretoken'] := token;
params.Values['username'] := txtUporabniskoIme.Text;
params.Values['password'] := txtGeslo.Text;
idHTTP.Post('http://www.ttaksa.si/login/', params, stream);
idHTTP.Get('http://www.ttaksa.si/objekti/export/?zacetni_datum=23.7.2015-12:00:00&format=xml&indent=2', stream);
stream.SaveToFile(txtFilename.Text);
wbUvoz.Navigate('File://' + txtFilename.Text);
finally
idHTTP.Free;
stream.Free;
params.Free;
end;
end;
procedure TForm1.IdHTTPOnRedirect(Sender: TObject; var dest: string;
var NumRedirect: Integer; var Handled: boolean; var VMethod: TIdHTTPMethod);
begin
Handled := True;
end;

DSSesssion in delphi Xe5

How to use DSSession to implements DataSnap authenticated sessions(HTTP/HTTPs)?????
My problems are:
I try to login into Login.html, then login complete Server Redirect into home.html
But in page Home.html not identified yet, So cant use Function.ServerMethod();
I wana to SetCredential(user:pass) in Home page used DSSession or anythings same.
In Home page , if not login, Redirect into Login again.
Before in Login.html confirm user and pass :
procedure TWebModule1.DSAuthenticationManager1UserAuthenticate(
Sender: TObject; const Protocol, Context, User, Password: string;
var valid: Boolean; UserRoles: TStrings);
var
session: TDSSession;
begin
//valid := True;
FormMain.Debug(['Before IsLogin : ',IsLogin],'?');
if not IsLogin then
IsLogin := (User = Password) and (user <> '');
valid := IsLogin;
FormMain.Debug(['IsLogin : ',IsLogin],'?');
FormMain.Debug(['UserAuthenticate :',User,Password],'?');
if valid = true then
FormMain.Debug(['UserAuthenticate : valid = true'],'?')
else
FormMain.Debug(['UserAuthenticate : valid = false'],'?');
if valid then
begin
Session := TDSSessionManager.GetThreadSession;
Session.PutData ('username', user);
UserRoles.Add ('standard');
if User = 'admin' then
UserRoles.Add ('admin');
end;
end;
Then redirect into Home.html. But in this page cant use Serverfunction(). ( errror 404, not Unauthorize)

events fql return empty array

I'm trying to retrieve users events using the facebook php sdk, but i'm stuck, the api return an empty array
$user = $me['id'];
$fql = "SELECT eid, name, start_time, end_time
FROM event
WHERE eid IN (SELECT eid
FROM event_member
WHERE uid = 1552544515)
ORDER BY start_time LIMIT 5";
$params = array(
'method' => 'fql.query',
'query' => $fql,
);
try {
$result = $facebook->api($params);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
thanks in advance.
If this is returning nothing, the most likely reason is that your user hasn't granted the user_events Permission during the Authentication flow.
Looking at your comments above, you may have added user_events to the permissions granted when a user goes through the Authenticated Referrals flow or via App Center, but regular users accessing the app directly need to go through one of the authentication flows from the document above, you're probably not doing this