CSharp · Console
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine("Without authorization:");
DoSomething(
(i,u) => { Console.WriteLine("Alpha " + i); return true; },
(i,u) => { Console.WriteLine("Beta " + i); return true; }
);
Console.WriteLine();
Console.WriteLine("Rockstar activity:");
DoSomething(
new Authorizer("rockstar").ActionToDo,
(i,u) => { Console.WriteLine("Alpha " + i); return true; },
(i,u) => { Console.WriteLine("Beta " + i); return true; }
);
Console.WriteLine();
Console.WriteLine("Guest activity:");
DoSomething(
new Authorizer("guest").ActionToDo,
(i,u) => { Console.WriteLine("Alpha " + i); return true; },
(i,u) => { Console.WriteLine("Beta " + i); return true; }
);
}
// third-party framework. cannot change the signature
public static void DoSomething(params Func<int, string, bool>[] actions)
{
var basicAuthUser = "davegrohl"; // obtained from browser's basic authentication
for(int i = 0; i < actions.Length; ++i)
{
var a = actions[i];
bool okToContinue = a(new Random().Next(10), basicAuthUser);
if (!okToContinue)
break;
}
}
}
class Authorizer
{
public string RoleAllowed { get; set; }
public Authorizer(string roleAllowed)
{
this.RoleAllowed = roleAllowed;
}
string GetRole(string basicAuthUser)
{
return "rockstar"; // davegrohl's role fetched from database
}
public bool ActionToDo(int i, string basicAuthUser)
{
// Database operation here.
// Get the role of basicAuthUser
var role = this.GetRole(basicAuthUser);
return role == this.RoleAllowed;
}
}