search_s search_ext_s search_s methods of python-ldap library doesn't return any Success response code - python-ldap

I am using search_ext_s() method of python-ldap to search results on the basis of filter_query, upon completion of search I get msg_id which I passed in result function like this ldap_object.result(msg_id) this returns tuple like this (100, attributes values) which is correct(I also tried result2, result3, result4 method of LDAP object), But how can I get response code for ldap search request, also if there are no result for given filter_criteria I get empty list whereas in case of exception I get proper message like this
ldap.SERVER_DOWN: {u'info': 'Transport endpoint is not connected', 'errno': 107, 'desc': u"Can't contact LDAP server"}
Can somebody please help me if there exists any attribute which can give result code for successful LDAP search operation.
Thanks,
Radhika

An LDAP server simply may not return any results, even if there was nothing wrong with the search operation sent by the client. With python-ldap you get an empty result list. Most times this is due to access control hiding directory content. In general the LDAP server won't tell you why it did not return results.
(There are some special cases where ldap.INSUFFICIENT_ACCESS is raised but you should expect the behaviour to be different when using different LDAP servers.)
In python-ldap if the search operation did not raise an exception the LDAP result code was ok(0). So your application has to deal with an empty search result in some application-specific way, e.g. by also raising a custom exception handled by upper layers.

Related

Google Calendar - SyncToken is missing in API response

I don't see nextSyncToken in the response. I followed the doc(https://developers.google.com/calendar/api/guides/sync) and paginated using nextPageToken but I couldn't see the nextSyncToken on the last page.
API Used: GET /calendars/primary/events?maxResults=10&singleEvents=true&pageToken=********
I don't know whether if I miss anything here. Could anyone help me with this?
I have seen from the response link on the other answer comment that you are using orderBy on the request.
This is why the nextSyncToken is not showing up.
As mentioned on the documentation on Events: list -> Parameters -> syncToken:
Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list request contain only entries that have changed since then. All events deleted since the previous list request will always be in the result set and it is not allowed to set showDeleted to False.
There are several query parameters that cannot be specified together with nextSyncToken to ensure consistency of the client state.
These are:
iCalUID
orderBy
privateExtendedProperty
q
sharedExtendedProperty
timeMin
timeMax
updatedMin
If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full synchronization without any syncToken.
Learn more about incremental synchronization.
Optional. The default is to return all entries.
You should remove the orderBy from the request to get the syncToken
Could you please provide the response from gcalendar API? It's hard to say more without detail information. I event don't know which language are you using.
Try to use a vendor library to sort that out:
a) https://packagist.org/packages/google/apiclient (for PHP)
b) https://www.npmjs.com/package/google-calendar (for JavaScript)
and/or
Try to use alternative endpoint: GET https://www.googleapis.com/calendar/v3/calendars/calendarId/events.

Microsoft Graph API delta query for channelMessages never returns a deltaLink

I'm trying to use delta query to get teams channel messages updates according this documentation: HERE
This is the request url:
https://graph.microsoft.com/beta/teams/<teamId>/channels/<channelId>/messages/delta
However, calling the returned nextLinks one after another never returns a deltaLink. There're too many pages of results and it causes my app to be throttled before ever getting a deltaLink from it.
In other delta query endpoints, $top is supported to limit the number of results returned. Usually I'm able to get a deltaLink after calling the nextLinks once or twice. But $top doesn't seem to have an effect in the channel messages endpoint.
So I tried appending another queryString ?odata.maxpagesize=10 to the request instead, and it seemed to work a week ago. I was able to get the deltaLink after 2 pages. But it looks like Microsoft might have changed the API and this workaround no longer works.
I also tried adding Prefer: odata.maxpagesize=10 in my request header according to this documentation: HERE
But the nextLink this generates is too long and it gives me this error instead:
HTTP Error 414. The request URL is too long.
Has anyone been able to use this delta for channel messages? Or have I done something wrong?

How to eliminate false success messages when implementing post-redirect-get pattern?

When implementing the post-redirect-get pattern in a web application, it is common for the final step in your server code to look something like this (pseudocode):
if (postSuccessful)
{
redirect("/some-page?success=true")
}
That is, the redirect URL has some kind of success parameter in the query string so that you know when to display a nice looking "Your form has been submitted!" message on your page. The problem with this is that the success=true persists in the query string when it's only needed to initialize the page. If the user refreshes the page or bookmarks it, they will receive a false success message even though no additional POST has taken place.
Is there an elegant solution to this that doesn't involve using JavaScript to eliminate success=true from both the query string and the browser history? This solution works, but definitely adds complexity to a page's load process.
You can use server side technology to implement this feature, without any JavaScript. The stes are listed below:
When post is successful, redirect to /some-page with current timestamp information:
if (postSuccessful)
{
redirect("/some-page?success=true&timestamp=1559859090747")
}
When server receives GET /some-page?success=true&timestamp=1559859090747 request, compare the timestamp parameter with the current timestamp, check whether it is within the last 3 seconds (or you can change this number according to the network environment).
If the timestamp parameter is within last 3 seconds, then it means this GET /some-page?success=true request is a result of server redirect. If not, then it's more like a result of "user refreshes the page or bookmarks it".
In server code that handling GET /some-page, render different HTML according to the result of step 3. Display the success message only when current access is a result of server redirect.

Diferentiate user not found from wrong credentials

When calling loginWithPassword I receive an error with code 403 in both cases: when the user doesn't exist and when the password is wrong. I know that theirs messages/reasons are different, but I think that comparing with string is not a good practice. Is there a different way of differentiating these cases?
UPDATE Using accounts-password
No real way of differentiating other than checking the error description string (that is what it is for).
You can always implement your own mechanism server-side (e.g, a method), but the default one sends a numeric error code (normally corresponding to the HTTP code - in this case, 403 forbidden), accompanied by a string.
They have not changed recently and it is fairly safe to depend on them, especially if it is not something mission-critical.
You could implement a method that checks for the existence of a user and then call that after a failed login attempt. If the user exists then you can display a bad password warning.
You could even check existence before the password is typed and put a green checkmark next to the username field if the user is found or a red X otherwise.
There are many ways to do this.

How to expose a validation API in a RESTful way?

I'm generally a fan of RESTful API design, but I'm unsure of how to apply REST principles for a validation API.
Suppose we have an API for querying and updating a user's profile info (name, email, username, password). We've deemed that a useful piece of functionality to expose would be validation, e.g. query whether a given username is valid and available.
What are the resource(s) in this case? What HTTP status codes and/or headers should be used?
As a start, I have GET /profile/validate which takes query string params and returns 204 or 400 if valid or invalid. But validate is clearly a verb and not a noun.
The type of thing you've described is certainly more RPC-style in its' semantics, but that doesn't mean you can't reach your goals in a RESTful manner.
There's no VALIDATE HTTP verb, so how much value can you get from structuring an entire API around that? Your story centers around providing users with the ability to determine whether a given user name is available - that sounds to me like a simple resource retrieval check - GET: /profile/username/... - if the result is a 404, the name is available.
What this highlights is that that client-side validation is just that - client side. It's a UI concern to ensure that data is validated on the client before being sent to the server. A RESTful service doesn't give a whit whether or not a client has performed validation; it will simply accept or reject a request based on its' own validation logic.
REST isn't an all-encompassing paradigm, it only describes a way of structuring client-server communications.
We have also encountered the same problem. Our reasoning for having the client defer to the server for validation was to prevent having mismatched rules. The server is required to validate everything prior to acting on the resources. It didn't make sense to code these rules twice and have this potential for them to get out of sync. Therefore, we have come up with a strategy that seems to keep with the idea of REST and at the same time allows us to ask the server to perform the validation.
Our first step was to implement a metadata object that can be requested from a metadata service (GET /metadata/user). This metadata object is then used to tell the client how to do basic client side validations (requiredness, type, length, etc). We generate most of these from our database.
The second part consist of adding a new resource called an analysis. So for instance, if we have a service:
GET /users/100
We will create a new resource called:
POST /users/100/analysis
The analysis resource contains not only any validation errors that occurred, but also statistical information that might be relevant if needed. One of the issues we have debated was which verb to use for the analysis resource. We have concluded that it should be a POST as the analysis is being created at the time of the request. However, there have been strong arguments for GET as well.
I hope this is helpful to others trying to solve this same issue. Any feedback on this design is appreciated.
You are confusing REST with resource orientation, there's nothing in REST that says you cannot use verbs in URLs. When it comes to URL design I usually choose whatever is most self-descriptive, wheather is noun or verb.
About your service, what I would do is use the same resource you use to update, but with a test querystring parameter, so when test=1 the operation is not done, but you can use it to return validation errors.
PATCH /profile?test=1
Content-Type: application/x-www-form-urlencoded
dob=foo
... and the response:
HTTP/1.1 400 Bad Request
Content-Type: text/html
<ul class="errors">
<li data-name="dob">foo is not a valid date.</li>
</ul>
A very common scenario is having a user or profile signup form with a username and email that should be unique. An error message would be displayed usually on blur of the textbox to let the user know that the username already exists or the email they entered is already associated with another account. There's a lot of options mentioned in other answers, but I don't like the idea of needing to look for 404s meaning the username doesn't exist, therefore it's valid, waiting for submit to validate the entire object, and returning metadata for validation doesn't help with checking for uniqueness.
Imo, there should be a GET route that returns true or false per field that needs validated.
/users/validation/username/{username}
and
/users/validation/email/{email}
You can add any other routes with this pattern for any other fields that need server side validation. Of course, you would still want to validate the whole object in your POST.
This pattern also allows for validation when updating a user. If the user focused on the email textbox, then clicked out for the blur validation to fire, slightly different validation would be necessary as it's ok if the email already exists as long as it's associated with the current user. You can utilize these GET routes that also return true or false.
/users/{userId:guid}/validation/username/{username}
and
/users/{userId:guid}/validation/email/{email}
Again, the entire object would need validated in your PUT.
It is great to have the validation in the REST API. You need a validation anyway and wy not to use it on the client side. In my case I just have a convention in the API that a special error_id is representing validation errors and in error_details there is an array of error messages for each field that has errors in this PUT or POST call. For example:
{
"error": true,
"error_id": 20301,
"error_message": "Validation failed!",
"error_details": {
"number": [
"Number must not be empty"
],
"ean": [
"Ean must not be empty",
"Ean is not a valid EAN"
]
}
}
If you use the same REST API for web and mobile application you will like the ability to change validation in both only by updating the API. Especialy mobile updates would take more than 24h to get published on the stores.
And this is how it looks like in the Mobile application:
The response of the PUT or POST is used to display the error messages for each field. This is the same call from a web application using React:
This way all REST API response codes like 200 , 404 have their meaning like they should. A PUT call responses with 200 even if the validation fails. If the call passes validation the response would look like this:
{
"error": false,
"item": {
"id": 1,
"created_at": "2016-08-03 13:58:11",
"updated_at": "2016-11-30 08:55:58",
"deleted_at": null,
"name": "Artikel 1",
"number": "1273673813",
"ean": "12345678912222"
}
}
There are possible modifications you could make. Maby use it without an error_id. If there are error_details just loop them and if you find a key that has the same name as a field put his value as error text to the same field.

Resources