User.Suspended always return false in octokit.net - github-api

I am using the following code to get a list of all GitHub Enterprise users, then I am trying to suspend those no longer in AD. The Suspend function works, but User.Suspended property always returns false.
var searhRequest = new SearchUsersRequest("type:user&page="+pageNumber+"&page_size=100");
githubUsers = await client.Search.SearchUsers(searhRequest);
client.User.Administration.Suspend(userId);

Yeah, I think the problem is that we were trying to cast the return value as a user when ultimately the call that this is making behind the scenes doesn't return that data. As a work around, I've just called the get user method to get the users after I've rounded up the original results.
It can probably be done better, but here's what I have right now
Task<SearchUsersResult> task;
List<User> users = new List<User>();
int page = 1;
do
{
task = github.Search.SearchUsers(new SearchUsersRequest("type:user&repos:>=0") { Page = page, PerPage = 500 });
task.Wait();
users.AddRange(task.Result.Items.ToList<User>());
page++;
}
while (users.Count < task.Result.TotalCount);
// Get all users by login (this calls the api once for every user you have)
var tasks = users.Select(u => github.User.Get(u.Login));
// Get all unsuspended users
var activeUsers = Task.WhenAll<User>(tasks).Result.Where<User>(u => !u.Suspended).ToList();
Note that in the result of the call doesn't include the "isSuspended" data (pulled from my local enterprise instance using fiddler and then sanitized)
{"login":"User1"
"id":45
"avatar_url":"http://github.com/avatars/u/45?"
"gravatar_id":""
"url":"http://github.com/api/v3/users/User1"
"html_url":"http://github.com/User1"
"followers_url":"http://github.com/api/v3/users/User1/followers"
"following_url":"http://github.com/api/v3/users/User1/following{/other_user}"
"gists_url":"http://github.com/api/v3/users/User1/gists{/gist_id}"
"starred_url":"http://github.com/api/v3/users/User1/starred{/owner}{/repo}"
"subscriptions_url":"http://github.com/api/v3/users/User1/subscriptions"
"organizations_url":"http://github.com/api/v3/users/User1/orgs"
"repos_url":"http://github.com/api/v3/users/User1/repos"
"events_url":"http://github.com/api/v3/users/User1/events{/privacy}"
"received_events_url":"http://github.com/api/v3/users/User1/received_events"
"type":"User"
"site_admin":false
"ldap_dn":"CN=User1
OU=CompanyDEVUsers
OU=Users
OU=Company
DC=Company
DC=com"
"score":1.0}

Related

How do I get Instagram posts from several accounts?

I would like to show the latest instagram posts from three different instagram users in one app. I control the instagram accounts, so it wouldn't be a problem to use APIs that require the user to accept access.
One method would be to add ?__a=1 at the end of their profile to get at json that contains this information, show the title as text in my app and load the picture from Instagram's CDN.
From what I can see, this isn't allowed by Instagram's terms, so I could easily see them banning the whole thing after some time.
Using Instagram's APIs (both Basic Display API or Graph) looks doubtful in an app, since they are based on tokens that should be kept server side.
Potentially I can configure a backend that does nothing but get the content, stores it with the single purpose of pushing it forward. I would think even this is against Instagram's terms, and sounds a bit over-kill.
Is there any methods I've missed?
(The Bot asked for some code, here's the JS I cannot use..)
function viewInsta(input_url) {
var url = input_url;
const p = url.split("/");
var t = '';
for (let i = 0; i < p.length; i++) {
if(i==2){
t += p[i].replaceAll('-', '--').replaceAll('.','-')+atob('LnRyYW5zbGF0ZS5nb29n')+'/';
} else { if(i != p.length-1){ t += p[i]+'/'; } else { t += p[i]; } }
}
// document.getElementById(this.id).src = encodeURI(t);
return '<img src="'+encodeURI(t)+'">';
}
var request = new XMLHttpRequest();
request.open("GET", "instagram.json", false);
request.send(null)
var my_JSON_object = JSON.parse(request.responseText);
var node_objects = my_JSON_object.graphql.user.edge_owner_to_timeline_media.edges;
node_objects.forEach(alert_function);
function alert_function(value){
var url_array = value.node.thumbnail_src.split('?');
var url = url_array[0];
document.getElementById("div1").innerHTML += value.node.thumbnail_src + viewInsta(value.node.thumbnail_src) + '<hr>';
console.log (value.node.thumbnail_src);
}
You'll need to use the Facebook Graph API, specifically Instagram, and do the calls from your backend.
https://developers.facebook.com/docs/instagram-api/reference/ig-user/media#get-media
This means you'll need to do oAuth and store the access tokens on your backend.
You should be able to get the posts with POST /{ig-user-id}/media

How to get groups that user belong to?

Using Graph Service, I have tried to get list of groups that user belong to. Here is my sample code:
var userMemberOf = null;
var userMemberGroups = null;
const GraphService = require('graph-service');
const ClientCredentials = require('client-credentials');
const tenant = 'my-company.com';
const clientId = '0b13aa29-ca6b-42e8-a083-89e5bccdf141';
const clientSecret = 'lsl2isRe99Flsj32elwe89234ljhasd8239jsad2sl=';
const credentials = new ClientCredentials(tenant, clientId, clientSecret);
const service = new GraphService(credentials);
service.get('/users/tnguyen482#my-company.com/memberOf').then(response => {
userMemberOf = response.data;
});
var settings = {
"securityEnabledOnly": true
}
service.post('/users/tnguyen482#my-company.com/getMemberGroups', settings).then(response => {
userMemberGroups = response.data;
});
The data return from both get & post method was an empty list. I have tried another user id but the result is the same. Am I correct when using method memberOf and getMemberGroups to get list of groups that user belong to? Does my sample code correct?
When the user is in no group graph will return an empty result.
Otherwise, when an error occured (e.g. accessDenied or user not found) an corresponding http-status with an errormessage will be returned (more information in the documentation).
The operations you are using seem to be correct.
If you want to rule out that your operations/code is incorrect, you should try executing the operations in the Graph Explorer.
Its a great tool for debugging and you can even login for access to your own data.

"User not found" Error when creating a child entity using ControllerB action, soon after an aspUser is created in controllerA

After the successful creation of an application user and the following line of code (in Register action in AccountController) :
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
I am trying to add a child object
var controller=DependencyResolver.Current.GetService<AnotherController>();
controller.ControllerContext = new ControllerContext(Request.RequestContext, controller);
var res = controller.Create(
new ChildEntity
{
ApplicationUserId = user.Id,
IsAcative = true
});
my create Method looks like this
public async Task<ActionResult> Create(ChildEntity entity)
{
if (ModelState.IsValid)
{
db.ChildEntity.Add(entity);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(entity);
}
My object is not created. the return valueres contains the error "user not found" propertyName : "ApplicationUserId"
Can anybody help me to understand what is going on?
ps : i have noticed that the User.Identity.GetUserId() return null !!! (may be fo some other reason, may be my problem is linked to this..)
First and foremost, the user principal is not populated until after the next page load. The sign-in process merely sets the auth cookie. That cookie needs to be sent back and the auth machinery needs to run (as part of the request pipeline), before you can get anything from User.
Second, what you're doing here is just absolutely wrong. If you want to reuse the user creation code, factor it out into another class that all your controllers can utilize. It's absolutely the wrong approach to try to new up a controller inside another action to call an action on that.

Retrieve role in jhipster immediately after Auth.login

I want to send a user to a particular view after login based on a role that person has. For example, I want to send a user with ROLE_STUDENT to a student page, and a person with ROLE_TEACHER to a teacher page. Unfortunately, if I call isInRole in the controller immediately after Auth.login, that fails. Specifically, in the login function (which I moved to main.controller.js so that the login dialog appears on the main page), I have code like this:
$scope.login = function () {
Auth.login({
username: $scope.username,
password: $scope.password
}).then(function (account, $state) {
Principal.identity(true);
$scope.authenticationError = false;
$scope.account = account;
$scope.isAuthenticated = Principal.isAuthenticated;
$scope.isInRole = Principal.isInRole;
if ($scope.isInRole('ROLE_STUDENT')) {
$scope.state.go('student_dashboard');
}
}).catch(function () {
$scope.authenticationError = true;
});
};
However, the isInRole method always returns false. If I debug it, I can see in principal.service.js shows that at this point, _authenticated is false and _identity is undefined.
Now, if I comment out the isInRole conditional in the controller, so that the user always goes to the student_dashboard page, I can put isInRole code on the student_dashboard page itself, and it works great. So, it appears that something is happening between the time of the redirect, and the time the target page loads, and I want to know what that is so that I can cause it to happen and thus determine if a user has a particular role and then redirect appropriately.
I believe your problem is with
Principal.identity(true);
This actually returns a promise which does an ajax call to update the principal user, so to use the principal functions you will need to do something like this
Principal.identity(true).then(function(profile) {
$scope.authenticationError = false;
$scope.account = account;
$scope.isAuthenticated = Principal.isAuthenticated;
$scope.isInRole = Principal.isInRole;
if ($scope.isInRole('ROLE_STUDENT')) {
$scope.state.go('student_dashboard');
}
});
Otherwise the current identity is undefined.

Xamarin: Issues with transitioning between controllers and storyboard views

I realize this might come across as a very basic question, but I just downloaded Xamarin three days ago, and I've been stuck on the same issue for two days without finding a solution.
Here is what I am trying to do:
Get user input, call API, parse JSON and pass data to another controller, and change views.
Here is what I have been able to do so far: I get the user input, I call the API, I parse the response back, write the token to a file, and I want to pass the remaining data to the second controller.
This is the code I am trying:
var verifyCode = Storyboard.InstantiateViewController("verify") as VerifyCodeController;
if (verifyCode != null)
{
this.NavigationController.PushViewController(verifyCode, true);
}
My storyboard setup:
Navigation controller -> routesTo -> FirstController
I have another UI Controller View set up with the following properties set:
storyboardid: verify
restorationid: verify
and I am trying to push that controller view onto the navigation controller.
Right now this line is erroring out:
var verifyCode = Storyboard.InstantiateViewController("verify") as VerifyCodeController;
giving me this error, which I don't know what it means: Could not find an existing managed instance for this object, nor was it possible to create a new managed instance.
Am I way off in my approach?
p.s: I cannot use the ctrl drag thing like the tutorial suggests because I have an asynchronous call. And I cannot under no circumstances make it synchronous. So all the page transition has to be manual.
EDIT
to anyone requesting more code or more info:
partial void registerButton_TouchUpInside (UIButton sender)
{
phone = registrationNumber.Text;
string url = url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
request.Method = "GET";
Console.WriteLine("Getting response...");
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
}
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string content = reader.ReadToEnd();
if (string.IsNullOrWhiteSpace(content))
{
//Console.WriteLine(text);
Console.Out.WriteLine("Response contained empty body...");
}
else
{
var json = JObject.Parse (content);
var token = json["token"];
var regCode = json["regCode"];
var aURL = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine (aURL, "app.json");
File.WriteAllText(filename, "{token: '"+token+"'}");
// transition to main view. THIS IS WHERE EVERYTHING GETS MESSED UP
var verifyCode = Storyboard.InstantiateViewController("verify") as VerifyCodeController;
if (verifyCode != null)
{
this.NavigationController.PushViewController(verifyCode, true);
}
}
}
}
}
Here is all the info for every view in my storyboard:
1- Navigation controller:
- App starts there
- The root is the register pager, which is the page we are currently working on.
2- The register view.
- The root page
- class RegisterController
- No storyboard id
- No restoration id
3- The validate view
- Not connected to the navigation controller initially, but I want it to be connected eventually. Do I have to connect it either way? Through a segue?
- class VerifyCodeController
- storyboard id : verify
- restoration id : verify
If you guys need more information I'm willing to post more. I just think I posted everything relevant.

Resources